.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