mapActions 工具函數會將 store 中的 dispatch 方法映射到組件的 methods 中。和 mapState、mapGetters 也類似,只不過它映射的地方不是計算屬性,而是組件的 methods 對象上。我們來直接看它的實現:
export function mapActions (actions) { const res = {} normalizeMap(actions).forEach(({ key, val }) => { res[key] = function mappedAction (...args) { return this.$store.dispatch.apply(this.$store, [val].concat(args)) } }) return res }
可以看到,函數的實現套路和 mapState、mapGetters 差不多,甚至更簡單一些,實際上就是做了一層函數包裝。為了更直觀地理解,我們來看一個簡單的例子:
import { mapActions } from 'vuex' export default { // ... methods: { ...mapActions([ 'increment' // 映射 this.increment() 到 this.$store.dispatch('increment') ]), ...mapActions({ add: 'increment' // 映射 this.add() to this.$store.dispatch('increment') }) } }
經過 mapActions 函數調用后的結果,如下所示:
import { mapActions } from 'vuex' export default { // ... methods: { increment(...args) { return this.$store.dispatch.apply(this.$store, ['increment'].concat(args)) } add(...args) { return this.$store.dispatch.apply(this.$store, ['increment'].concat(args)) } } }
.