有时候我们觉得一个vue文件体积太大,想把其中的弹窗(el-dialog)单独拿出去,
随之而来的,可能是各种关于父子组件传值的麻烦事,

这里记录一个最简单的方法:
父组件:

<el-button type="primary" @click="childVisible=true">打开弹窗</el-button>

<childDialog :dialogVisible.sync="childVisible"></childDialog>
import childDialog from './childDialog.vue'
export default {
    components:{
        childDialog
    },
    data() {
        return {
            childVisible: false,

子组件:

<template>
  <el-dialog
    title="提示"
    :visible.sync="dialogVisible"
    width="30%"
    :close-on-click-modal="false"
    :before-close="closeMe">
    <span>这是一段信息</span>
    <span slot="footer" class="dialog-footer">
        <el-button @click="closeMe">取 消</el-button>
        <el-button type="primary">确 定</el-button>
    </span>
    </el-dialog>
</template>

<script>
export default {
    props: {
        dialogVisible:{
            type: Boolean
        }
    },
    methods:{
        closeMe(done){
            this.$emit('update:dialogVisible', false)
        }
    }
}
</script>

用这种方式就不需要两层的显示判断了(父组件一个v-if + 子组件的一个:visible.sync)
用:before-close是为了防止子组件直接修改props的值

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐