??在一些情況下,可能會需要對一個 prop 進(jìn)行雙向綁定。事實上洋措,這正是Vue1.x中的 .sync修飾符所提供的功能蜘渣。當(dāng)一個子組件改變了一個 prop 的值時淌铐,這個變化也會同步到父組件中所綁定的值。這很方便蔫缸,但也會導(dǎo)致問題腿准,因為它破壞了單向數(shù)據(jù)流的假設(shè)。由于子組件改變 prop 的代碼和普通的狀態(tài)改動代碼毫無區(qū)別拾碌,當(dāng)光看子組件的代碼時吐葱,完全不知道它何時悄悄地改變了父組件的狀態(tài)。這在 debug 復(fù)雜結(jié)構(gòu)的應(yīng)用時會帶來很高的維護(hù)成本校翔,上面所說的正是在 2.0 中移除 .sync 的理由弟跑。
從 2.3.0 起重新引入了 .sync 修飾符,但是這次它只是作為一個編譯時的語法糖存在防症。它會被擴(kuò)展為一個自動更新父組件屬性的 v-on 偵聽器孟辑。
<comp :foo.sync="bar"></comp>
會被擴(kuò)展為:
<comp :foo="bar" @update:foo="val => bar = val"></comp>
當(dāng)子組件需要更新 foo 的值時,它需要顯式地觸發(fā)一個更新事件:
this.$emit('update:foo', newValue)
因此蔫敲,可以使用.sync來簡化自定義事件的操作饲嗽,實現(xiàn)子組件向父組件的數(shù)據(jù)傳遞。
<div id="app">
<parent></parent>
</div>
<script src="https://unpkg.com/vue"></script>
<script>
var childNode = {
template: `
<div class="child">
<div>子組件數(shù)據(jù):{{childMsg}}</div>
<input v-model="childMsg">
<button @click=add >+1</button>
</div>
`,
data(){
return{
childMsg: 0
}
},
methods:{
add(){
this.childMsg++;
this.$emit('update:foo',this.childMsg);
}
}
};
var parentNode = {
template: `
<div class="parent">
<p>父組件數(shù)據(jù):{{msg}}</p>
<child :foo.sync="msg"></child>
</div>
`,
components: {
'child': childNode
},
data(){
return {
'msg':0
}
}
};
// 創(chuàng)建根實例
new Vue({
el: '#app',
components: {
'parent': parentNode
}
})
</script>