//父组建: <myConfirm :isShow="isShowConfirm" :title="title" :content="content"></myConfirm> import { myConfirm } from "@/components"; components:{ myConfirm }, data() { return { title:'提示', content:'是否删除?', isShowConfirm:false, }; }, methods:{ doDel(){ let ids = []; const that = this; that.isShowConfirm = true; //让组件显示 }, } //子组件: <template> <div class="confirm"> <Modal v-model="isShow" width="320" class-name="loginout-model" :closable="false" @on-ok="onOk" @on-cancel="onCancel"> <div style="text-align:center"> <h3>{{title}}</h3> <p>{{content}}</p> </div> </Modal> </div> </template> export default { components: { }, props: ['isShow','title','content'], data(){ return { }; }, watch:{ }, created() { }, computed:{ }, methods: { onOk(){}, onCancel(){} }, mounted(){ } };这时,点击父组建的删除,的确可以弹出子组件,当点击子组件的取消或者确认按钮,总之更改了isShow,就会报错:
[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: "isShow"
这是因为子组件的v-model更改了isShow的值,而在VUE中,子组件是无权限更改props的。所以,得借助“第三者”,这里就不详细探讨了,可以查看《如何在Vue2中实现组件props双向绑定》,写的很好,一看就明白了,下面贴出修改代码:
//父组建: <myConfirm :isShow="isShow" :title="title" :content="content" @closeConfirm="closeConfirm"></myConfirm> import { myConfirm } from "@/components"; components:{ myConfirm }, data() { return { title:'提示', content:'是否删除?', isShow:false, }; }, methods:{ doDel(){ let ids = []; const that = this; that.isShow = true; //让组件显示 }, closeConfirm(val){ //子组件通知父组件更改isShow(并非子组件更改isShow) this.isShow = val; } } //子组件: <template> <div class="confirm"> <Modal v-model="showFlag" width="320" class-name="loginout-model" :closable="false" @on-ok="onOk" @on-cancel="onCancel"> <div style="text-align:center"> <h3>{{title}}</h3> <p>{{content}}</p> </div> </Modal> </div> </template> export default { components: { }, props: ['isShow','title','content'], data(){ return { //强行更改isShow会报错,因为子组件更改props,不会影响父组件,props只能父组件改变,子组件没有权限改变 //这里创建一个showFlag作为isShow的副本,更改showFlag就会更改isShow,就会影响到父组件的isShow,否则父组件的isShow不会变化 showFlag:this.isShow }; }, watch:{ //因为isShow是父组件改变,而子组件没有用它来显示,而使用它的副本showFlag来更改显示,所以isShow被父组件更改了,要实时更新到showFlag上。 isShow(val){ this.showFlag = val; }, //监听当showFlag变成flase的时候,通知父组件将isShow也变成false,否则下次点击,将不会弹出 showFlag(val){ if(!val){ this.$emit('closeConfirm',val); } } }, created() { }, computed:{ }, methods: { onOk(){}, onCancel(){ this.showFlag = false } }, mounted(){ } };