2.3.0+ 新增
在有些情況下钠四,我們可能需要對一個 prop 進行“雙向綁定”幔嫂。不幸的是瘪撇,真正的雙向綁定會帶來維護上的問題港庄,因為子組件可以變更父組件倔既,且在父組件和子組件都沒有明顯的變更來源鹏氧。
這也是為什么我們推薦以 update:myPropName 的模式觸發(fā)事件取而代之。舉個例子把还,在一個包含 title prop 的假設(shè)的組件中,我們可以用以下方法表達對其賦新值的意圖:
this.$emit('update:title', newTitle)
然后父組件可以監(jiān)聽那個事件并根據(jù)需要更新一個本地的數(shù)據(jù) property吊履。例如:
<text-document
v-bind:title="doc.title"
v-on:update:title="doc.title = $event"
></text-document>
為了方便起見,我們?yōu)檫@種模式提供一個縮寫,即 .sync 修飾符:
<text-document v-bind:title.sync="doc.title"></text-document>
注意帶有 .sync 修飾符的 v-bind 不能和表達式一起使用 (例如 v-bind:title.sync=”doc.title + ‘!’” 是無效的)袖迎。取而代之的是,你只能提供你想要綁定的 property 名燕锥,類似 v-model。
當(dāng)我們用一個對象同時設(shè)置多個 prop 的時候归形,也可以將這個 .sync 修飾符和 v-bind 配合使用:
<text-document v-bind.sync="doc"></text-document>
這樣會把 doc 對象中的每一個 property (如 title) 都作為一個獨立的 prop 傳進去,然后各自添加用于更新的 v-on 監(jiān)聽器厚棵。
將 v-bind.sync 用在一個字面量的對象上,例如 v-bind.sync=”{ title: doc.title }”婆硬,是無法正常工作的,因為在解析一個像這樣的復(fù)雜表達式的時候彬犯,有很多邊緣情況需要考慮。
例子
<!DOCTYPE html>
<html lang="en">
<head>
<title>使用sync更改父級傳值</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
Vue.component("ComponentA", {
props:["info"],
template:`
<div>
我是子節(jié)點
<button @click="handleClick">點擊我改變父級</button>
</div>
`,
methods: {
handleClick() {
let arr = [1,2,3]
this.$emit("update:data", arr);
}
},
})
const app = new Vue({
el:"#app",
data:{
info:{
data:[]
},
},
template:`
<div>
我是父級節(jié)點
<ComponentA :data.sync="info.data"></ComponentA>
{{info.data}}
</div>
`,
})
</script>
</body>
</html>