vue2 父子组件间的双向数据绑定 (el-dialog问题)
先推荐下自己的另一篇文章vue父子组件传值,兄弟组件传值涉及到里面相关的内容为3. 子组件触发父组件方法($emit)4.props双向数据绑定(.sync)问题描述二次封装dialog,关闭时须将关闭的状态返回给父组件.(父子组件传值)代码实现父组件<template><div class="parent"><h1>我是父组件,我...
·
先推荐下自己的另一篇文章
问题描述
二次封装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)
}
}
更多推荐
已为社区贡献14条内容
所有评论(0)