javascript - 请问下面的函数写法什么意思?

查看:69
本文介绍了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传入进去,这样的原理是什么??这是自己半个月前写的代码,现在看怎么也不理解了。。

解决方案

去看看源码就知道了。

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)
}

这篇关于javascript - 请问下面的函数写法什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆