javascript - 請問下面的函數(shù)寫法什么意思?
問題描述
在vuex中的mutations中定義的一個函數(shù),在組件中調(diào)用
//store.js在mutations中定義addCart:function (state,{goodIndex,foodIndex}) { state.goods[goodIndex].foods[foodIndex].count++; },
//組件中調(diào)用methods:{ ...mapMutations([’addCart’,’removeCart’,’setCart’]), addCartItem:function(){this.setCart({goodIndex:this.goodIndex,foodIndex:this.foodIndex}); }}
我的問題是為什么在調(diào)用setCart函數(shù)的時候不用傳入state參數(shù),目測如果調(diào)用的時候不傳state參數(shù)的話,addCart函數(shù)執(zhí)行的時候就會自動將在store中的state傳入進(jìn)去,這樣的原理是什么??這是自己半個月前寫的代碼,現(xiàn)在看怎么也不理解了。。
問題解答
回答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 } // 在這里調(diào)用了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’)
相關(guān)文章:
1. Span標(biāo)簽2. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””3. css - 求推薦適用于vue2的框架 像bootstrap這種類型的4. docker-machine添加一個已有的docker主機問題5. css - 關(guān)于div自適應(yīng)問題,大家看圖吧,說不清6. SessionNotFoundException:會話ID為null。調(diào)用quit()后使用WebDriver嗎?(硒)7. android新手一枚,android使用httclient獲取服務(wù)器端數(shù)據(jù)失敗,但是用java工程運行就可以成功獲取。8. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問題。9. java - Collections類里的swap函數(shù),源碼為什么要新定義一個final的List型變量l指向傳入的list?10. python - django如何每次調(diào)用標(biāo)簽的時候都取隨機數(shù)據(jù)
