常規(guī)使用方法:
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['setActive'])
// 如果是某一個module下的mutation,需要帶上namespace
// 格式: mapMutations(namespace,[mutationName])
...mapMutations('home', ['setActiveList']), // ?? 數(shù)組形式
...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
})
從上述代碼可以看出其內部進行了相關的綁定操作~