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. 如何解決docker宿主機(jī)無法訪問容器中的服務(wù)?2. angular.js - 輸入郵箱地址之后, 如何使其自動(dòng)在末尾添加分號(hào)?3. javascript - 如何使用nodejs 將.html 文件轉(zhuǎn)化成canvas4. javascript - html5的data屬性怎么指定一個(gè)function函數(shù)呢?5. docker-compose中volumes的問題6. 在mac下出現(xiàn)了兩個(gè)docker環(huán)境7. python - Scrapy存在內(nèi)存泄漏的問題。8. javascript - 后臺(tái)管理系統(tǒng)左側(cè)折疊導(dǎo)航欄數(shù)據(jù)較多,怎么樣直接通過搜索去定位到具體某一個(gè)菜單項(xiàng)位置,并展開當(dāng)前菜單9. angular.js - $stateChangeSuccess事件在狀態(tài)跳轉(zhuǎn)的時(shí)候不執(zhí)行?10. java如何生成token?
