vue+elementUi弹框组件抽离el-dialog对话框组件两种写法

本文介绍了两种在Vue.js中实现父子组件通信并控制对话框显示的方法。第一种是通过props从父组件传入值,子组件内部监听并同步更新;第二种是父组件通过v-if直接控制对话框显示,子组件仅通过$emit触发关闭方法。这两种方式都详细展示了组件模板和脚本部分的实现细节。
摘要由CSDN通过智能技术生成

第一种:

父组件传入一个值控制,子组件内部监听传入的值,然后赋值给内部的值进行更改。还需要在@close关闭方法进行$emit父组件的值传入false以关闭对话框。

1、组件内部

<template>
  <el-dialog
    title="提示"
    :visible.sync="dialogVisible"
    width="30%"
    @close="$emit('update:childShow', false)"
  >
    <span>这是一段信息</span>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  props:{
    childShow:{
      type:Boolean,
      default:false
    }
  },
  data(){
    return {
      dialogVisible:false
    }
  },
  watch:{
    childShow(val){
      this.dialogVisible = val
    }
  }
};
</script>

2、页面使用

<template>
  <div>
    <el-button @click="directoryShow = true">显示</el-button>
    <showDialog :childShow.sync="directoryShow" />
  </div>
</template>

<script>
// 别名引入写法
import showDialog from "@/components/showDialog.vue";
export default {
  components: { showDialog },
  data(){
    return {
      directoryShow:false
    }
  }
};
</script>

第二种:

直接在父组件用if判断,子组件内部保持一直显示状态,需要关闭对话框时只需$emit调父组件的方法,在父组件上将if的值设置为false即可。
1、组件内部

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

<script>
export default {
  data(){
    return {
      dialogVisible:true
    }
  }
};
</script>

<style></style>

2、父组件使用

<template>
  <div>
    <el-button @click="directoryShow = true">显示</el-button>
    <showDialog v-if="directoryShow" @close="directoryShow = false" />
  </div>
</template>

<script>
import showDialog from "@/components/showDialog.vue";
export default {
  components: { showDialog },
  data() {
    return {
      directoryShow: false,
    };
  },
};
</script>

<style></style>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值