vuex 中關於 mapActions 的作用


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

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM