在mutations中注冊的setCart方法://store.js
mutations:{ setCart(state,foodIndex){
Vue.set(state.goods.foods[foodIndex],"count",1);
}
}組件中提交mutations并使用setCart方法//childComponent.vuemethods:{
setCart(foodIndex){
this.$store.commit('setCart',this.foodIndex);
},
},
addCartItem:function (event) {
if (!this.food.count){
this.setCart(this.foodIndex);
}else{
this.addCart(this.foodIndex)
return
}
},結果會報錯,this.foodIndex is undefined ,在created中console了this.foodIndex,結果正常,我直接傳數值給setCart:this.addCart(0)依然會報錯:this.foodIndex is undefined會不會我在store.js注冊的mutations方法不對?
2 回答

qq_笑_17
TA貢獻1818條經驗 獲得超7個贊
首先,貼一下 你定義 this.foodIndex
的代碼,確定你有定義這個變量
其次,貼出來的methods的代碼有問題
建議改為
methods:{
setCart (foodIndex){
this.$store.commit('setCart', foodIndex);
},
addCartItem (event) {
if (!this.food.count){
this.setCart(this.foodIndex);
}else{
this.addCart(this.foodIndex)
return
}
}
如果還有問題,請貼出更詳細的代碼
添加回答
舉報
0/150
提交
取消