.sync作用:實現(xiàn)父子組件數(shù)據(jù)之間的雙向綁定
一:.sync與v-model的共同點
都是語法糖,都可以實現(xiàn)父子組件中的數(shù)據(jù)的雙向通信鸠项。
.sync實現(xiàn)通信的方式:
// 父組件
<template>
<div>
{{ num }}
<MyCom1 :a.sync="num"/>
// 等價于
<!-- <MyCom1 :a="num" @update:a="val=>num=val"/> -->
</div>
</template>
<script>
import MyCom1 from './MyCom1.vue'
export default {
components: { MyCom1 },
data() {
return {
num: 100
}
}
}
</script>
// 子組件
<template>
<div>自定義組件com1-{{ a }}
<button @click="$emit('update:a', a+1)">+1</button>
</div>
</template>
<script>
export default {
props: {
a: { type: Number, required: true }
}
}
</script>
v-model實現(xiàn)通信的方式:(默認(rèn)是input事件)
// 父組件
<template>
<div>
{{ num }}
<MyCom1 v-model="num" />
// 等價于
<!-- <MyCom1 :value="num" @input="val=>num=val" /> -->
</div>
</template>
<script>
import MyCom1 from './MyCom1.vue'
export default {
components: { MyCom1 },
data() {
return {
num: 100
}
}
}
</script>
// 子組件
<template>
<div>自定義組件com1-{{ value }}
<button @click="$emit('input', value+1)">+1</button>
</div>
</template>
<script>
export default {
props: {
value: { type: Number, required: true }
}
}
</script>
二:.sync與v-model的不共同點
- 格式不同
.sync 父組件 :a.sync 子組件 @update:a
v-model 父組件 v-model: 子組件 @(input 祟绊, value)
- 一個組件可以多個屬性用.sync修飾符,可以同時"雙向綁定多個“prop”牧抽,而并不像v-model那樣,一個組件只能有一個记舆。
例:
// 父組件
<template>
<div>
{{ num }}
<MyCom1 :a.sync="num" :b.sync="num2" />
</div>
</template>
<script>
import MyCom1 from './MyCom1.vue'
export default {
components: { MyCom1 },
data() {
return {
num: 100,
num2: 100
}
}
}
</script>
// 子組件
<template>
<div>自定義組件com1-{{ a }}
// 更改事件名字即可
<button @click="$emit('update:a', a+1)">+1</button>
</div>
</template>
<script>
export default {
props: {
a: { type: Number, required: true }
b: { type: Number, required: true }
}
}
</script>
三:功能的作用場景:
1.v-model針對更多的是最終操作結(jié)果呼巴,是雙向綁定的結(jié)果,是value诊赊,是一種change操作府瞄。
比如:輸入框的值、多選框的value值列表鲸郊、樹結(jié)構(gòu)最終綁定的id值列表(ant design和element都是)货邓、等等...
2..sync針對更多的是各種各樣的狀態(tài)秆撮,是狀態(tài)的互相傳遞换况,是status,是一種update操作舒裤。
比如:組件loading狀態(tài)觉吭、子菜單和樹結(jié)構(gòu)展開列表(狀態(tài)的一種)、某個表單組件內(nèi)部驗證狀態(tài)伴鳖、等等...