網(wǎng)站建設(shè)個(gè)體營業(yè)執(zhí)照合肥seo推廣排名
.sync修飾符作用
.sync修飾符是一個(gè)語法糖,可以簡化父子組件通信操作,當(dāng)子組件想改變父組件數(shù)值時(shí),父組件只需要使用.sync修飾符,子組件使用props接收屬性,再使用this.$emit('update:屬性', 值);就可以實(shí)現(xiàn)子組件更新父組件數(shù)據(jù)的操作。
以下將用el-dialog例子展示傳統(tǒng)父子通信及使用.sync修飾符后的父子通信區(qū)別:
傳統(tǒng)父子通信
//父組件
<template><div><button @click="openDialog">打開對(duì)話框</button>
<!--給子組件傳遞dialogVisible屬性--><ChildDialog :dialogVisible="dialogVisible" @updateDialogVisible="handleDialogVisibleChange"></ChildDialog></div>
</template><script>
import ChildDialog from './ChildDialog.vue';export default {components: {ChildDialog},data() {return {dialogVisible: false};},methods: {openDialog() {this.dialogVisible = true;},
//收到子組件傳來的新值,更新dialogVisible handleDialogVisibleChange(newVisible) {this.dialogVisible = newVisible;}}
};
</script>//子組件
<template><el-dialog :visible="dialogVisible" @close="closeDialog"><span>這是對(duì)話框內(nèi)容</span></el-dialog>
</template><script>
export default {props: {dialogVisible: {type: Boolean}},methods: {closeDialog() {
//自定義監(jiān)聽事件,將新值傳給父組件this.$emit('updateDialogVisible', false);}}
};
</script>
.sync修飾符父子通信
//父組件
<template><div><button @click="dialogVisible = true">打開對(duì)話框</button>
<!--父組件不需要再綁定監(jiān)聽事件獲取新值再賦給dialogVisible.sync修飾符可以自動(dòng)完成數(shù)據(jù)更新操作,更簡潔--><ChildDialog :dialogVisible.sync="dialogVisible"></ChildDialog></div>
</template><script>
import ChildDialog from './ChildDialog.vue';export default {components: {ChildDialog},data() {return {dialogVisible: false};}
};
</script>//子組件
<template><el-dialog :visible="dialogVisible" @close="closeDialog"><span>這是對(duì)話框內(nèi)容</span></el-dialog></template><script>
export default {props: {dialogVisible: {type: Boolean}},methods: {closeDialog() {
//告訴父組件哪個(gè)屬性更新并且傳新值this.$emit('update:dialogVisible', false);}}
};
</script>
歡迎指正!