vue组件传值报错: Instead, use a data or computed property based on the prop's value. Prop being mutated: "item"

问题:父组件往子组件传值,后在method方法中修改了该值,然后报错如下:

经排查,发现原因如下:

prop是单向绑定,不能更改数据,只能由父组件传输过来

解决方法:

1、使用$emit 和 $on 将改变后的数据传给父组件,父组件接收后在赋值给当前要修改的数据

this.$emit('returnItem', data)

在父组件中使用方法获取

returnItem (data) {
  # 赋值
}

2、使用.sync修饰符与$emit(update:xxx)

父组件

<comp :item.sync="item"></comp>

子组件

this.$emit('update:item',data)

驼峰法 和 - 写法的区别

1、使用.sync修饰符,变量应该使用驼峰法:

this.$emit('update:fatherNum',100); 
 //......
<father v-bind:father-num.sync="test"></father>

2、不适用 .sync 修饰符,变量应该使用 - ,即father-num

this.$emit('update:father-num',100);  
//......
<father v-bind:father-num="test" v-on:update:father-num="test=$event" ></father>
原文地址:https://www.cnblogs.com/wangyingblock/p/14442917.html