v-model的本质

v-model是v-bind:vlaue和v-on:input的语法糖

  1. <div id="app">
  2. <!-- <input type="text" v-model="number"> -->
  3. <input type="text" v-bind:value="number" v-on:input="number=$event.target.value">
  4. {{number}}
  5. </div>
  6. <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
  7. <script>
  8. let app = new Vue({
  9. el: "#app",
  10. data:{
  11. number: 0
  12. }
  13. })
  14. </script>

v-model在组件中使用

  1. <div id="app">
  2. {{number}}
  3. <!-- <my-component :value='number' @input="number=$event"></my-component> -->
  4. <my-component v-model="number"></my-component>
  5. </div>
  6. <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
  7. <script>
  8. Vue.component('my-component',{
  9. props:['value'],
  10. template: `<div><button @click="$emit('input', ++value)">+1</button></div>`
  11. })
  12. let app = new Vue({
  13. el: "#app",
  14. data:{
  15. number: 0
  16. }
  17. })
  18. </script>

v-model在render函数中使用

  1. <div id="app">
  2. {{number}}
  3. <my-component v-model="number"></my-component>
  4. </div>
  5. <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
  6. <script>
  7. Vue.component('my-component',{
  8. render(createElement){
  9. let self = this
  10. return createElement('input', {
  11. domProps:{
  12. value: self.value
  13. },
  14. on:{
  15. input(event){
  16. self.$emit('input',event.target.value)
  17. }
  18. }
  19. })
  20. }
  21. })
  22. let app = new Vue({
  23. el: '#app',
  24. data:{
  25. number: 0
  26. }
  27. })
  28. </script>