javascript - 請問下面的函數寫法什么意思?
問題描述
在vuex中的mutations中定義的一個函數,在組件中調用
//store.js在mutations中定義addCart:function (state,{goodIndex,foodIndex}) { state.goods[goodIndex].foods[foodIndex].count++; },
//組件中調用methods:{ ...mapMutations([’addCart’,’removeCart’,’setCart’]), addCartItem:function(){this.setCart({goodIndex:this.goodIndex,foodIndex:this.foodIndex}); }}
我的問題是為什么在調用setCart函數的時候不用傳入state參數,目測如果調用的時候不傳state參數的話,addCart函數執行的時候就會自動將在store中的state傳入進去,這樣的原理是什么??這是自己半個月前寫的代碼,現在看怎么也不理解了。。
問題解答
回答1:去看看源碼就知道了。
export const mapMutations = normalizeNamespace((namespace, mutations) => { const res = {} normalizeMap(mutations).forEach(({ key, val }) => { val = namespace + val res[key] = function mappedMutation (...args) { if (namespace && !getModuleByNamespace(this.$store, ’mapMutations’, namespace)) {return } // 在這里調用了commit方法 return this.$store.commit.apply(this.$store, [val].concat(args)) } }) return res})
下面是commit方法的定義
this.commit = function boundCommit (type, payload, options) { // store 就是你想要的答案 return commit.call(store, type, payload, options)}回答2:
this.setCart()被映射為this.$store.commit(’setCart’)
相關文章:
1. css - 如何把一個視圖放在左浮動定位的視圖的上面?2. javascript - axios請求回來的數據組件無法進行綁定渲染3. php多任務倒計時求助4. python的正則怎么同時匹配兩個不同結果?5. javascript - vue中怎么使用原生js插件6. javascript - 請問下面代碼中的...是擴展運算符還是操作運算符?這樣寫是什么意思?7. javascript - 小demo:請教怎么做出類似于水滴不斷擴張的效果?8. css - 子元素跑到父元素外面9. MySQL的聯合查詢[union]有什么實際的用處10. javascript - jquery怎么讓a標簽跳轉后保持tab的樣式
