javascript - What does the following function writing mean?
我想大声告诉你
我想大声告诉你 2017-06-26 10:56:52
0
2
730

A function defined in mutations in vuex is called in the component

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

My question is why there is no need to pass in the state parameter when calling the setCart function. Visually, if the state parameter is not passed when calling, the addCart function will automatically pass in the state in the store when it is executed, so What is the principle? ? This is the code I wrote half a month ago, but now I don’t understand it. .

我想大声告诉你
我想大声告诉你

reply all(2)
伊谢尔伦

Just go and look at the source code and you will know.

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

The following is the definition of the commit method

this.commit = function boundCommit (type, payload, options) {
    // store 就是你想要的答案
    return commit.call(store, type, payload, options)
}
扔个三星炸死你

this.setCart() is mapped to this.$store.commit('setCart')

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template