本人使用iview+vue,在父页面打开一个modal,然后再子组件里要关闭modal
父页面是这样的:
<template>
<div>
<Row :style="{'margin-bottom':'10px'}">
<Button type="primary" @click="dg.maintenanceGroup=true">添加</Button>
</Row>
<Modal
v-model="dg.maintenanceGroup"
:title="dg.title"
width="600">
<maintenanceGroup :modalShow="dg.maintenanceGroup">
</maintenanceGroup>
</Modal>
</div>
</template>
就是调用add方法打开modal ,modal是一个子页面引用进来,下面是子页面:
<template>
<div>
<span>子页面</span>
<Button type="primary" icon="ios-search" @click="modalShow=false">关闭</Button>
</div>
</template>
父页面给子页面传值,使用:modalShow="dg.maintenanceGroup",子页面 props: ['modalShow'],这样子页面就接到父页面的值了,但是我在子页面点击关闭将modalshow=false就会报错,错误如下:
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: "modalShow" (found in component )
组件内不能修改props的值,同时修改的值也不会同步到组件外层,即调用组件方不知道组件内部当前的状态是什么,那么我们要解决这个问题就需要实现双向绑定,意思就是在父组件中修改值和在子组件中修改值都会同步到对方属性上,这样才会达到双向绑定
解决办法就是在子组件中声明响应的变量,初始赋值props接收的值,然后对外部变量和内部变量监听,同步修改值
data() {
return {
showModal:this.modalShow,
submitLoading:this.saveLoading,
}
},
watch:{
//监听外部对值得改变,同步到本地变量上
modalShow(value){
this.showModal=value;
},
//监听本地变量改变,通知外部变量改变
showModal(value){
this.$emit("changeShowModal",value);
},
},
methods: {
},
props: ['modalShow'],
reated() {}
}
子组件监听完毕后就给父组件加上时间绑定
<maintenanceGroup :modalShow="dg.maintenanceGroup" @changeShowModal="changeModal">
然后method里加上响应方法
changeModal(value){
this.dg.maintenanceGroup = value;
},
好了 大功告成,特此记录