| 我们知道响应式数据是vue的一个特点,通过v-mold能够实现数据的实时响应,但是我们也应该清楚v-model 是语法糖,本质还是父子组件间的通信。其实质上还是通过 props,父组件给子组件传值再通过 Events up,子组件使用 $emit 触发事件将数据传回给父组件。
 vue2.x
 
<child v-model="msg"></child>
<template>
 <div>
  <input type="text" v-model="newValue">
 </div>
</template>
<script>
export default {
 props:{
  value:{
   type:String,
   default:''
  }
 },
 computed:{
  newValue:{
   get:function(){
    return this.value
   },
   set:function(value){
    this.$emit('input',value)
   }
  }
 }
}
</script>
<child :value="msg" @input="msg=$events"></child>
 vue3.x 
<child v-model="name"></child>
  
<template>
 <input type="text" v-model="newValue">
</template>
<script>
export default {
 props:{
  modelValue:{
   type:String,
   default:''
  }
 },
 computed:{
  newValue:{
   get:function(){
    return this.modelValue
   },
   set:function(value){
    this.$emit('update:modelValue',value)
   }
  }
 }
}
</script>
<child-comp :modelValue="msg" @update:modelValue="msg=$event"></child> 
 tips.sync修饰符
 
<child v-model="name" :age.sync="age"></child>
<child v-model:name="name" v-model:age="age"></child>
emits:['update:name','update:age'],
 |