vue2.0 改变子组件从父组件传递过来的值报错Avoid mutating a prop directly since the value will be overwritten whenever

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: "selectType"


实现vue2.0 饿了么过程中父组件food.vue像子组件ratingSelect.vue传递了selectType值之后,在子组件ratingSelect.vue中改变selectType的值会出现上述警告以下就是解决此问题:

父组件:food.vue


mounted:function(){
Bus.$on("selectType",(selectType) =>{//子组件数据改变之后传递给父组件

this.selectType = selectType;
});

}

子组件ratingSelect.vue在子组件声明一个中间变量typeSelect,避免直接改变父组件传递过来的selectType

props:{

selectType:{
type:Number,
default:All
}
},
data(){
return{
typeSelect:this.selectType
}
},
methods:{
select(type,_event){
if(!_event._constructed){
return;
}
this.typeSelect = type;
//通知父组件selectType修改
Bus.$emit("selectType",this.typeSelect); 
}
},


以上也涉及到子组件怎样向父组件传递数据,通过一个空的Vue实例作为中央事件总线

具体实现如下:(在父子组件中各自引入)

import Vue from 'vue';
export default new Vue();

你可能感兴趣的:(vue2.0 改变子组件从父组件传递过来的值报错Avoid mutating a prop directly since the value will be overwritten whenever)