日常開發(fā)中經(jīng)常遇到的一個(gè)場(chǎng)景,父組件有很多操作,需要彈窗,例如:
<template> <div class="page-xxx"> //點(diǎn)擊打開新增彈窗 <button>新增</button> //點(diǎn)擊打開編輯彈窗 <button>編輯</button> //點(diǎn)擊打開詳情彈窗 <button>詳情</button> <Add :showAdd="false"></Add> <Edit :showEdit="false"></Edit> <Detail :showDetail="false"></Detail> </div></template>
子組件:
<div class="page-add"> <el-dialog :visible="dialogVisible" @close="handleClose"></el-dialog></div><script>export default { data() { return { dialogVisible: false, } }, methods: { handleClose(val) { this.dialogVisible= false }, },}</script>如何實(shí)現(xiàn)子組件和父組件模態(tài)框狀態(tài)的同步
方案一:使用.sync 修飾符
父組件:
<template> <div class="page-xxx"> //點(diǎn)擊打開新增彈窗 <button @click="show = true">新增</button> <Add :show.sync="show"></Add> </div></template>
子組件:
<div class="page-add"> <el-dialog:visible="dialogVisible" @close="handleClose"></el-dialog></div><script>export default { props: { show: { type: Boolean } }, watch: { show(value) { this.dialogVisible= value } }, data() { return { dialogVisible: false, } }, methods: { handleClose(val) { this.$emit('update:show', false); }, },}</script>方案二:使用v-model
父組件:
<template> <div class="page-xxx"> //點(diǎn)擊打開新增彈窗 <button @click="show = true">新增</button> <Add v-model="show"></Add> </div></template>
子組件:
<div class="page-add"> <el-dialog :visible="dialogVisible" @close="handleClose"></el-dialog></div><script>export default { props: { show: { type: Boolean } }, watch: { show(value) { this.dialogVisible= value } }, data() { return { dialogVisible: false, } }, methods: { handleClose(val) { this.$emit('input', false) }, },}</script>computed OR watch ?
對(duì)于上面的兩種方案,子組件內(nèi)部還可以使用計(jì)算屬性的寫法
computedexport default { props: { show: { type: Boolean } }, computed: { dialogVisible: { get() { return this.show }, set(value) { return this.$emit('input', value) }, }, }, methods: { handleClose(val) {}, },}
新聞熱點(diǎn)
疑難解答
圖片精選