.sync和v-model的区别
v-model
<!--父组件-->
<template>
<!--v-model 是语法糖-->
<Child v-model="model"></Child>
<!--相当于下面的代码-->
<!--v-model的默认行为是input,默认prop是value-->
<Child :value="model" @input="model = $event"></Child>
</template>
你也可以通过model选项来修改v-model的默认行为和prop
//子组件
model: {
prop: 'checked',
event: 'change'
}
所以相应的父组件使用v-model的时候的等效操作为:
<template>
<Child :checked="model" @change="model = $event"></Child>
<template>
v-model通常用于表单控件,因为这样子组件有更强的控制能力
.sync
<!--父组件-->
<template>
<!--.sync添加于v2.4,他能用于修改传递到子组件中的属性,-->
<Child :value.sync="model"></Child>
<!--等效于下面的代码-->
<Child :value = "model" @update:value = "model = $event"></Child>
</template>
<!--子组件-->
<input :value="value" @input = "$emit('update:value', $event.target.value)"/>
这里绑定的属性名称的更改,相应的属性名也会变化
<!--父组件-->
<template>
<Child :foo.syn="model"></Child>
</template>
<!--子组件-->
<input :value = "foo" @input = "$emit('update:value', $event.target.value)"/>
- .sync的原理用到了子组件向父组件派发事件的$emit方法。其应用场景为子组件想修改父组件传递的属性
sync修饰符的控制能力都在父组件,事件名称也是相对固定的update:xx