javascript - 請(qǐng)問下面的函數(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ù),目測(cè)如果調(diào)用的時(shí)候不傳state參數(shù)的話,addCart函數(shù)執(zhí)行的時(shí)候就會(huì)自動(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. 360瀏覽器與IE瀏覽器有何區(qū)別???2. mysql 怎么做到update只更新一行數(shù)據(jù)?3. javascript - 新浪微博網(wǎng)頁(yè)版的字?jǐn)?shù)限制是怎么做的4. node.js - mysql如何通過knex查詢今天和七天內(nèi)的匯總數(shù)據(jù)5. mysql 插入數(shù)值到特定的列一直失敗6. python - 在使用Pycharm時(shí)經(jīng)常看到如下的樣式,小括號(hào)里紅色的部分是什么意思呢?7. javascript - 用jsonp抓取qq音樂總是說回調(diào)函數(shù)沒有定義8. 怎么在網(wǎng)頁(yè)中設(shè)置圖片進(jìn)行左右滑動(dòng)9. sublime可以用其他編譯器替換嗎?10. python 合并dict
