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函数执行的时候就会自动将在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. java固定键值转换,使用枚举实现字典?2. javascript - 移动端开发 H5 页面在 iOS手机上无法实现 长按复制文本 求解决3. 如何解决tp6在zend中无代码提示4. java - HTTPS双向认证基础上有无必要再进行加签验签?5. python - flask学习,user_syy添加报role is invalid keyword for User.6. vim - win10无法打开markdown编辑器7. java - 读写锁中 写锁的降级问题8. javascript - 有没有类似高铁管家的时间选择插件9. html - 如何使用用户输入的数据去运行一个数学公式,最后怎么返回。10. css - BEM 中块(Block)有木有什么标准 何时决定一个部分提取为块而不是其父级的元素呢(Element)?~
