javascript - 請(qǐng)問(wèn)下面的函數(shù)寫法什么意思?
問(wèn)題描述
在vuex中的mutations中定義的一個(gè)函數(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}); }}
我的問(wèn)題是為什么在調(diào)用setCart函數(shù)的時(shí)候不用傳入state參數(shù),目測(cè)如果調(diào)用的時(shí)候不傳state參數(shù)的話,addCart函數(shù)執(zhí)行的時(shí)候就會(huì)自動(dòng)將在store中的state傳入進(jìn)去,這樣的原理是什么??這是自己半個(gè)月前寫的代碼,現(xiàn)在看怎么也不理解了。。
問(wè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. angular.js - webpack build后的angularjs路由跳轉(zhuǎn)問(wèn)題2. java - Activity中的成員變量被賦值之后,Activity被回收的時(shí)候內(nèi)存才會(huì)被釋放嗎3. java - web項(xiàng)目中,用戶登陸信息存儲(chǔ)在session中好 還是cookie中好,取決于什么?4. 數(shù)組按鍵值封裝!5. 為什么bindClass訪問(wèn)不了的?6. 為什么 必須在<ul> 下建立 <li> 在建<a>?7. tp5.0,param獲取全部參數(shù)8. 請(qǐng)求一個(gè)數(shù)據(jù)返回內(nèi)容為空或者錯(cuò)誤如何再次請(qǐng)求幾次9. 單擊登錄按鈕無(wú)反應(yīng)10. 我寫的哪里有錯(cuò)?請(qǐng)大神幫忙查看一下。
