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函數執(zhí)行的時候就會自動將在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. 輸入地址報以下截圖錯誤,怎么辦?2. angular.js - angularJs ngRoute怎么在路由傳遞空字符串及用ng-switch取得3. javascript - ie11以下單擊打開不了file,雙擊可以。求解?4. vim里的高亮javascript的javascript.vim 已經放到syntax里了,但是不行。5. html5 - video ios不能播放怎么辦?6. android - xml的drawable作背景,是否會產生錯誤7. python - pip install出現下面圖中的報錯 什么原因?8. node.js - node中MYSQL的異步問題9. javascript - 求助一個關于indexedDB的問題10. 我何時應該在Java中使用JFrame.add(component)和JFrame.getContentPane()。add(component)
