Vue2中实现组件props双向绑定
来源:18-11 ratingselect组件(5)

ZZ辉
2016-12-31
遇到控制台输出Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders···这样的问题,可以如下解决。
3回答
-
Urchiola_
2017-04-04
您确定可以给监听里面的方法 直接赋值??
10 -
ZZ辉
提问者
2016-12-31
vuejs2.0中,任何试图在组件内修改通过props传入的父组件数据都会报以上错误。参考教程如何在Vue2中实现组件props双向绑定。拿selectType举个栗子:
首先在ratingselect.vue组件中创建
data: function () { return { mySelectType: this.selectType, }; }, watch: { selectType: function (val) { this.mySelectType = val; }, mySelectType: function (val) { this.$emit('on-type-change', val); }, },
然后改methods,我们在ratingselect组件中使用副本数据mySelectType来操作,当它发生变化,会向父组件$emit().
methods: { select: function (type, event) { if (!event._constructed) { return; } this.mySelectType = type; } }
最后在父组件food.vue中
<ratingselect :select-type="selectType" :only-content="onlyContent" :desc="desc" :ratings="food.ratings" @on-type-change="onTypeChange"></ratingselect>
以及在其methods中加入
methods: { onTypeChange: function (val) { this.selectType = val; } },
这样父组件的selectType也得到改动。解决了$dispatch()的问题。
如有纰漏,欢迎修改!
10 -
独孤银
2017-04-11
子组件通过props传入的值,在methods里通过$emit()向父级派发带参事件,因为父子组件双向绑定,就可以直接修改selectType的值
子组件
methods: {
changeselecttype(type, event) {
if (!event._constructed) {
return;
}
this.$parent.$emit('changeslecttype', type);
}
}父组件
created() {
this.$on('changeslecttype', (type) => {
this.selectType = type;
});
}00
相似问题