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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM