問題:父組件往子組件傳值,后在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>