vuex之mapMutation
2021-08-12 本文已影响0人
studentliubo
常规使用方法:
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
})
从上述代码可以看出其内部进行了相关的绑定操作~