- 相同点 :
都是语法糖 , 都可以实现父子组件中的数据的双向通信;
- 不同点 :
格式不同 : v-model = “age” , :age.sync = “age”
绑定的事件不同 : v-model : @input + :value , :age.sync : @update:age
v-model只能使用一次 , .sync修饰符可以使用多次。
父组件
<Child v-model="myData" :age.sync ="age" :name.sync ="name" ></Child>
子组件
<template>
<div>
<button @click="handleClick(value-1)">减少</button>
<input type="text" v-model='value'>
<button @click="handleClick(value+1)">添加</button>
<div>年龄默认值是:{{age}}</div>
<div>姓名默认值是:{{name}}</div>
<button @click="changeAge(value+1)">改变年龄</button>
<button @click="changeName('zdy')">改变姓名</button>
</div>
</template>
<script>
export default {
props:{
value:{
type:Number,
default:0,
},
age:{
type:Number,
default:0,
},
name:{
type:String,
default:'dy',
}
},
methods:{
handleClick(newValue){
this.$emit('input',newValue);
},
changeAge(newValue){
this.$emit('update:age',newValue);
},
changeName(newValue){
this.$emit('update:name',newValue);
}
}
}
</script>
