美文网首页
vuex之mapMutation

vuex之mapMutation

作者: studentliubo | 来源:发表于2021-08-12 16:17 被阅读0次

常规使用方法:

import { mapMutations } from 'vuex'

methods: {
  ...mapMutations(['setActive'])
    // 如果是某一个module下的mutation,需要带上namespace
    // 格式: mapMutations(namespace,[mutationName])
    ...mapMutations('home', ['setActiveList']), // 🚀 数组形式
    ...mapMutations('home', { setActives: 'setActiveList' }), // 🚀 对象形式
    // 如果有多个namespace 那就多写几个mapMutations
}

原理:

下面👇是源码部分:

export const mapMutations = normalizeNamespace((namespace, mutations) => {
  const res = {}
  if (__DEV__ && !isValidMap(mutations)) {
    console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object')
  }
  normalizeMap(mutations).forEach(({ key, val }) => {
    res[key] = function mappedMutation (...args) {
      // Get the commit method from store
      let commit = this.$store.commit
      if (namespace) {
        const module = getModuleByNamespace(this.$store, 'mapMutations', namespace)
        if (!module) {
          return
        }
        commit = module.context.commit
      }
      return typeof val === 'function'
        ? val.apply(this, [commit].concat(args))
        : commit.apply(this.$store, [val].concat(args))
    }
  })
  return res
})

从上述代码可以看出其内部进行了相关的绑定操作~

相关文章

网友评论

      本文标题:vuex之mapMutation

      本文链接:https://www.haomeiwen.com/subject/modinktx.html