Vuex系列之 Action 的使用


Action 用于处理异步任务。

如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在 Action 中还是要通过触发Mutation 的方式间接变更数据。

一、定义 Action

// 创建store数据源,提供唯一公共数据
export default new Vue.Store({
    
    
	// state 中存放的就是全局共享的数据
	state: {
    
    
		count: 0
	},
	mutations: {
    
    
		add(state) {
    
    
			// 变更状态
			state.count++;
		},
		addN(state, step) {
    
    
			state.count += step;
		}
	},
	actions: {
    
    
		addAsync(context) {
    
    
			setTimeout(() => {
    
    
				// 在 actions 中,不能直接修改 state 中的数据;
				// 必须通过 context.commit() 触发某个 mutation 才行
				context.commit("add");
			}, 1000);
		}
	},
	getters: {
    
    }
});

触发 actions 异步任务时携带参数:第二个参数即为传递的参数

// 创建store数据源,提供唯一公共数据
export default new Vue.Store({
    
    
	// state 中存放的就是全局共享的数据
	state: {
    
    
		count: 0
	},
	mutations: {
    
    
		add(state) {
    
    
			// 变更状态
			state.count++;
		},
		addN(state, step) {
    
    
			state.count += step;
		}
	},
	actions: {
    
    
		addAsync(context) {
    
    
			setTimeout(() => {
    
    
				// 在 actions 中,不能直接修改 state 中的数据;
				// 必须通过 context.commit() 触发某个 mutation 才行
				context.commit("add");
			}, 1000);
		},
		addNAsync(context, step) {
    
    
			setTimeout(() => {
    
    
				context.commit("addN", step);
			}, 1000);
		}
	},
	getters: {
    
    }
});

二、触发 Action

1、触发 actions 的第一种方式

通过dispatch触发store的异步函数,第一个参数为异步函数名,第二个参数为携带的参数。

this.$store.dispatch("addAsync");

或者

this.$store.dispatch("addNAsync", 5);

2、触发 actions 的第二种方式:

2.1、从 vuex 中按需导入 mapActions 函数

import {
    
     mapActions } from "vuex";

通过刚才导入的 mapActions 函数,将需要的 actions 函数,映射为当前组件的 methods 方法:

2.2、将指定的 actions 函数,映射为当前组件的 methods 函数

methods: {
    
    
	...mapActions(["addAsync", "addNAsync"])
}

写在最后

如果你感觉文章不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
如果你觉得该文章有一点点用处,可以给作者点个赞;\\*^o^*//
如果你想要和作者一起进步,可以微信扫描二维码,关注前端老L~~~///(^v^)\\\~~~
谢谢各位读者们啦(^_^)∠※!!!

猜你喜欢

转载自blog.csdn.net/weixin_62277266/article/details/128439042