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

.

vuexmapActions是一个工具函数,它的作用是将store中的dispatch方法映射到组件的methods中。\[1\]这样做的好处是可以在组件中直接调用映射后的函数来触发对应的action。\[2\]使用mapActions的场景是当一个方法需要在多个页面和组件上使用时,可以通过mapActions来简化代码。\[1\]在组件中引入并调用mapActions,然后通过调用映射后的函数来触发对应的action。\[2\]相比于直接使用this.$store.dispatch()来触发action,使用mapActions可以更简洁地调用多个action。\[3\]只需要将需要触发的action函数名传入mapActions中,然后在组件中调用这些函数即可触发对应的action。 #### 引用[.reference_title] - *1* [Vue/Vuex (actions) 核心概念 使用方法、辅助函数 mapActions使用方法说明](https://blog.youkuaiyun.com/m0_64494670/article/details/127834964)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [vuexmapActions的概念及用法](https://blog.youkuaiyun.com/jiangjunyuan168/article/details/126962600)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值