先推荐下自己的另一篇文章

问题描述

二次封装dialog,关闭时须将关闭的状态返回给父组件.(父子组件传值)

代码实现

父组件

<template>
  <div class="parent">
    <h1>我是父组件,我的数据dialog是{{dialog}}</h1>
    <el-button @click="open">打开dialog</el-button>
    <child :dialogswitch.sync="dialog" ></child>
  </div>
</template>

<script>
import Child from "./child";
export default {
  data(){
    return{
      dialog:false
    }
  },
  components:{
      Child
  },
  methods:{
    open(){
      this.dialog = true
    }
  }
}
</script>

子组件

<template>
  <el-dialog title="提示" :visible.sync="dialogswitch" width="30%">
    <span slot="footer" class="dialog-footer">
      <el-button @click="closebtn">取 消</el-button>
      <el-button type="primary" @click="submitbtn">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'child',
  props: ['dialogswitch'],
  methods:{
      closebtn(){
          this.$emit('update:dialogswitch',false)
      },
      submitbtn(){
          console.log('确定');
      }
  }
}
</script>

运行效果图
在这里插入图片描述

由图可以看出

  • 点击取消的时候,dialog关闭.dialog由false->true->false
  • 点击dialog外面(或者上面的叉号),dialog关闭,并报错.虽然关闭了,但是父组件的dialog的值还是true, dialog由false->true,在点按钮就不好使了(因为父组件的dialog值已经是true了)
    [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "dialogswitch"
    [vue warn]:避免直接改变属性,因为每当父组件重新呈现时,该值都将被覆盖。相反,使用基于属性值的数据或计算属性。

原因

<el-dialog title="提示" :visible.sync="dialogswitch" width="30%">这里使用了 .sync

解决方案

1. 将.sync删除,添加:show-close='false'

就不能点击dialog外面(点击叉号),来关闭dialog了.
只能通过调用this.$emit('update:dialogswitch',false)来关闭

<el-dialog title="提示" :visible="dialogswitch" :show-close='false' width="30%">

2. 添加一个中间变量,负责传递父子组件中的开关

父组件不变
子组件,添加一个中间变量,负责传递父子组件中的开关.dialog关闭时的回调方法
在这里插入图片描述
代码

<template>
  <el-dialog title="提示" :visible.sync="show" @close='handleclose' width="30%">
    <span slot="footer" class="dialog-footer">
      <el-button @click="closebtn">取 消</el-button>
      <el-button type="primary" @click="submitbtn">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'child',
  props: ['dialogswitch'],
  data(){
      return {
          show: this.dialogswitch,
      }
  },
  watch:{
      dialogswitch(val){
          this.show = val;
      },
  },
  methods:{
      handleclose(){
          this.$emit('update:dialogswitch',false)
      },
      closebtn(){
          this.show = false;
        //   this.$emit('update:dialogswitch',false)
      },
      submitbtn(){
          console.log('确定');
      }
  }
}
</script>

若没有关闭回调方法
只需监听下中间变量show,为false时,调用this.$emit('update:dialogswitch',false)

show(val){
    if(!val){
      this.$emit('update:dialogswitch',false)
    }
}
Logo

前往低代码交流专区

更多推荐