Vue1.0升级至2.0之后,直接在子组件修改父组件的值是会报错的 目的是为了阻止子组件影响父组件的数据
报错警告: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:
直接在子组件修改父组件的值是不支持的。
子组件
用props来接收父组件的值:
props:{
ratings: {//评价
type: Array,
default() {
return [];
}
},
selectType:{//选择的评价类型
type: Number,
default: ALL
},
onlyContent:{//是否是勾选,只看内容评价
type: Boolean,
default: false
},
desc: {
type: Object,
default(){
return {
all: '全部',
positive: '满意',
negative: '不满意'
}
}
}
},
父组件
data中给值进行初始化
selectType: ALL,
onlyContent: true, //先设置组件一开始显示有内容的评价
desc: { //desc做了改变
all: '全部',
positive: '推荐',
negative: '吐槽'
子组件
1.data中定义两个新的变量(要更改的父组件的变量赋给新的变量)
data(){
return {
selectTypeChild: this.selectType,
onlyContentChild: this.onlyContent
}
},
2.写事件更改父组件数据
methods:{
select(type, event){
if (!event._constructed) { //去掉自带click事件的点击
return;
}
this.selectTypeChild = type;
//派发事件通知父组件food.vue selectType的改变,将type值传出去
this.$emit('distribute', 'selectType', type); //selectType要跟父组件中data定义的同名
},
toggleonly(event){
if (!event._constructed) { //去掉自带click事件的点击
return;
}
this.onlyContentChild = !this.onlyContentChild;
this.$emit('distribute', 'onlyContent', this.onlyContentChild);
}
}
父组件
<ratingselect @distribute="distributeFn"
:ratings="food.ratings"
:select-type="selectType"
:only-content="onlyContent"
:desc="desc">ratingselect>
@distribute="distributeFn"绑定子组件传来的事件接收数据
//父组件事件接收子组件传来的数据
distributeFn(type, data){
//this指向vue,this[type]取data中的跟type相同的属性
this[type] = data;
this.$nextTick(() => {
this.scroll.refresh();
})
}
结束!
总结:props只能单向传递,如果子组件要更改父组件的数据,需要上述流程进行更改!