javascript - 請問下面的函數(shù)寫法什么意思?
問題描述
在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}); }}
我的問題是為什么在調(diào)用setCart函數(shù)的時(shí)候不用傳入state參數(shù),目測如果調(diào)用的時(shí)候不傳state參數(shù)的話,addCart函數(shù)執(zhí)行的時(shí)候就會自動(dòng)將在store中的state傳入進(jìn)去,這樣的原理是什么??這是自己半個(gè)月前寫的代碼,現(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. 網(wǎng)頁爬蟲 - python爬蟲翻頁問題,請問各位大神我這段代碼怎樣翻頁,還有價(jià)格要登陸后才能看到,應(yīng)該怎么解決2. python如何不改動(dòng)文件的情況下修改文件的 修改日期3. 算法 - python 給定一個(gè)正整數(shù)a和一個(gè)包含任意個(gè)正整數(shù)的 列表 b,求所有<=a 的加法組合4. python - thrift 返回 TSocket read 0 bytes 求助!!!!5. javascript - 微信h5發(fā)送圖文信息,部分設(shè)備點(diǎn)擊“發(fā)送”按鈕時(shí)沒反應(yīng),問題較難重現(xiàn),如何能找到可能存在問題的點(diǎn)?6. javascript - 微信小程序里怎么把頁面轉(zhuǎn)成圖片分享7. python 正則表達(dá)式提取8. python - 求一個(gè)在def中可以實(shí)現(xiàn)調(diào)用本def滿足特定條件continue效果的方法(標(biāo)題說不太清楚,請見題內(nèi)描述)9. javascript - JS用ajax爬取百度外賣店家信息10. python - Pycharm調(diào)試代碼進(jìn)行列表遍歷時(shí),如何直接賦值指定元素
