在Vue2.0中,项目开发时遇到的问题。
在子组件定义
<script> export default { props:['displaySelf'] } </script>
在父组件调用子组件并对displaySelf赋值后,在点击按钮进行动态修改值时问题来了。
Avoid mutating a prop directly since the value will be
overwritten whenever the parent component re-
由于在vue2.0中作了修改,props只能单向传值,如果该值时动态的且在子组件对该值作了处理就会导致问题发生。因为vue组件是相对独立体,Props里的值是被认为是“不可改变的”,当你去做更改时就会出问题。
搞清楚问题之后,那我们就好改了。这里直接抛弃原来的做法,只需要在你的父组件初始化调用时添加“ref”并调用即可。
初始化子组件调用:
<StationsLinesWindow
ref="StationsLinesWindow">
</StationsLinesWindow>
父组件methods中通过“that.$refs.声明的子组件名.子组件中对应的方法名”来调用子组件方法:
methods:{
drawing(){
var that = this;
that.$refs.StationsLinesWindow.closePanel("close-button");
},
}
子组件StationsLinesWindow中,此时不在props中定义displaySelf ,而将其放入data()中:
data(){
return{
displaySelf : false,
}
},
methods:{
closePanel(type){
if(type == "close-button"){
this.$confirm('关闭窗口将不会上传您添加或修改的数据,请确认是否已上传,是否继续?','提示',{
confirmButtonText: '确认关闭',
cancelButtonText: '取消',
type: 'warning'
}).then(()=>{
this.displaySelf = false;
}).catch(()=>{});
}
},
}
测试无问题。