vue 中 .sync 修飾符,是 2.3.0+ 版本新增的功能
在有些情況下,我們可能需要對一個 prop 進行“雙向綁定”。不幸的是,真正的雙向綁定會帶來維護上的問題,因為子組件可以變更父組件,且在父組件和子組件兩側都沒有明顯的變更來源。
這也是為什么我們推薦以 update:myPropName
的模式觸發事件取而代之。舉個例子,在一個包含 title
prop 的假設的組件中,我們可以用以下方法表達對其賦新值的意圖:
在子組件中,props 中 使用 title,然后修改 title 為新的值,並通知父組件:
this.$emit('update:title', newTitle)
然后父組件可以監聽那個事件並根據需要更新一個本地的數據 property。例如:
<text-document v-bind:title="doc.title" v-on:update:title="doc.title = $event"
></text-document>
為了方便起見,我們為這種模式提供一個縮寫,即 .sync
修飾符:
<text-document v-bind:title.sync="doc.title"></text-document>
當我們用一個對象同時設置多個 prop 的時候,也可以將這個 .sync
修飾符和 v-bind
配合使用:
<text-document v-bind.sync="doc"></text-document>
這樣會把 doc
對象中的每一個 property (如 title
) 都作為一個獨立的 prop 傳進去,然后各自添加用於更新的 v-on
監聽器。
實際應用場景:
vue dialog 彈窗中使用
父組件引入一個子組件,子組件是一個彈窗,父組件控制彈窗打開,子組件關閉彈窗時通知父組件,父組件不用再監聽更新事件
父組件:
<template>
<div>
<el-button @click="open">打開彈窗</el-button>
<my-dialog :visible.sync="dialogVisible" />
</div>
<template>
<script>
export default {
data() {
return {
dialogVisible: false
}
},
methods: {
open() {
this.dialogVisible = true
}
}
}
</script>
子組件中:
需要使用 :before-close 來處理關閉后的操作,不要使用@close 方法,因為傳給父組件visible為false后,子組件會監聽到visible的變化,會再執行@close方法
<template> <el-dialog title="新建"
width="70%"
:visible="visible"
:before-close="close"
@close="close"
>
<div>子組件</div>
</el-dialog>
</template>
props: { visible: { type: Boolean, require: true, default: false } }, methods: { close() { this.$emit('update:visible', false) } }