最近在使用element-ui的Dialog组件二次封装成独立组件使用时,子组件需要将关闭dialog状态返回给父组件,也就是实现父子组件之间双向数据绑定问题,实例代码如下:
父组件:
<template>
<div>
<el-button type="primary" @click="openDialog">点击打开Dialog</el-button>
<childComponent title="Dialog对话框" :openStatus="openStatus" @dialog="closeDialog"></childComponent>
</div>
</template>
<script>
import childComponent from './ChildComponent'
export default {
data () {
return {
openStatus: false
}
},
components: {
childComponent
},
methods: {
openDialog () {
this.openStatus = true
},
closeDialog (data) {
// 子组件触发父组件事件,修改openStatus的值
this.openStatus = data
}
}
}
</script>
子组件:
<template>
<el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
<span>Dialog对话框</span>
<span slot="footer" class="dialog-footer">
<el-button @click="handleClose">取 消</el-button>
<el-button type="primary" @click="handleClose">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
props: {
title: String,
openStatus: Boolean
},
data () {
return {
// dialogVisible变量缓存openStatus数据
dialogVisible: this.openStatus
}
},
// 监听父组件对props属性openStatus的修改,并同步导组件内的dialogVisible属性
watch: {
openStatus (val) {
this.dialogVisible = val
}
},
methods: {
handleClose () {
// 关闭对话框时向父组件发送事件通知
this.$emit('dialog', false)
}
}
}
</script>
参考:https://segmentfault.com/a/1190000011783590