vue弹窗组件封装、控制显示隐藏最佳方案

4,422 阅读1分钟

原理:

弹窗组件作用域内部定义变量,父子页面不通过传变量的方式通信,子页面声明一个方法控制组件显示,父页面通过ref直接调用子页面的方法控制子页面显示隐藏。

弹窗文件封装vue文件:

<template>
    <el-dialog
        :visible.sync="visible"
        @close="close">
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="restart()">保 存</el-button>
        </div>
    </el-dialog>
</template>
<script>
    export default {
        name: "dia-log",
        data() {
            return {
                visible: false,
            }
        },
        methods: {
            open() {
                this.visible = true;
            },
            close() {
                this.visible = false;
            }
        }
    }
</script>

<style scoped>

</style>

父页面引入弹窗组件,通过ref访问子页面方法控制弹窗显示

<template>
    <div class="main">
        <a @click="showDialog">打开弹窗</a>
        <dia-log ref="dialog"></dia-log>
    </div>
</template>

<script>
    import DiaLog from './dia-log'
    export default {
        name: "father",
        component: {
            'dia-log': DiaLog
        },
        methods: {
            showDialog() {
                this.$refs.dialog.open();
            }
        }
    }
</script>

<style scoped>

</style>