element ui 之el-dialog的显示与隐藏
- el-dialog作为子组件的显示与隐藏
方法一:
父级组件parent.vue:
<template>
<!-- 按钮,点击设置showFlag为true,即打开弹出框 -->
<el-button @click="showFlag = true"></el-button>
<!-- 将showFlag传递给子组件 -->
<child :showFlag="showFlag" @closeChildDialog="closeChildDialog"></child>
</template>
<script>
export default {
name: 'parent',
props:[],
data () {
return {
showFlag: false
}
},
methods: {
/**
* 接受子组件调用的关闭弹出框方法
*/
closeChildDialog () {
this.showFlag = false
}
}
}
</script>
子组件child.vue:
<template>
<el-dialog title="子组件弹出框" :visible.sync="dialogVisible" @close="closeDialog">
<div slot="footer">
<el-button @click="closeDialog">取 消</el-button>
<el-button type="primary" @click="closeDialog">确 定</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
name: 'child',
props: {
// 接受父级组件的显示标记,用于被watch
showFlag: {
type: Boolean
}
},
data () {
return {
// 子组件自己的显示标记,用于真正切换dialog的显示/隐藏
dialogVisible: false
}
},
methods: {
/**
* 关闭弹出框事件,触发父级组件的closeChildDialog方法
*/
closeDialog () {
this.$emit('closeChildDialog')
}
},
watch: {
// 观察父级组件的showFlag,并将showFlag的最新值设置给dialogVisible
showFlag (newVal, oldVal) {
this.dialogVisible = newVal
}
}
}
</script>
方法二:
父组件 parent.vue
<template>
<!-- 按钮,点击设置showFlag为true,即打开弹出框 -->
<el-button @click="showFlag = !showFlag"></el-button>
<!-- 将showFlag传递给子组件 -->
<child @closeChildDialog="closeChildDialog"></child>
</template>
<script>
export default {
name: 'parent',
props:[],
data () {
return {
showFlag: false
}
},
methods: {
/**
* 接受子组件调用的关闭弹出框方法
*/
closeChildDialog () {
this.showFlag = false
}
}
}
</script>
但是子组件稍有不同,代码如下:
子组件 child.vue
<template>
<el-dialog title="子组件弹出框" :visible.sync="dialogVisible" @close="closeDialog">
<div slot="footer">
<el-button @click="closeDialog">取 消</el-button>
<el-button type="primary" @click="closeDialog">确 定</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
name: 'child',
data () {
return {
dialogVisible: true
}
},
methods: {
/**
* 关闭弹出框事件,触发父级组件的closeChildDialog方法
*/
closeDialog () {
this.$emit('closeChildDialog')
}
},
}