Vuex 中Mutation 和Action介绍
在 Vuex 中,Mutation(变更) 和 Action(动作) 都是修改状态的核心机制,但职责和使用场景不同:
Mutation(变更)
核心特性:
- 同步操作:必须是同步函数(直接修改状态)。
- 直接修改状态:唯一能修改 Vuex
state
的方式。 - 可追踪性:每个 mutation 会被开发工具记录,便于调试时间旅行(state 快照)。
- 不可异步:不能在 mutation 中执行异步操作(否则状态变更无法追踪)。
定义方式:
// store.js
const store = new Vuex.Store({state: {count: 0},mutations: {// 基本 mutation(无参数)INCREMENT(state) {state.count++;},// 带参数的 mutationADD(state, payload) {state.count += payload.value;}}
});
触发方式:
组件中通过 commit
触发:
this.$store.commit('INCREMENT');
this.$store.commit('ADD', { value: 10 }); // 参数作为载荷(payload)
Action(动作)
核心特性:
- 支持异步:可在 action 中执行异步操作(如 API 请求)。
- 提交 Mutation:不直接修改状态,而是通过
commit
调用 mutation。 - 复杂逻辑:适合处理业务逻辑(如多个 mutation 组合、条件判断)。
- 返回 Promise:支持异步操作链式调用(如
dispatch
后处理)。
定义方式:
// store.js
actions: {// 基本 action(无参数)incrementAsync({ commit }) {setTimeout(() => {commit('INCREMENT');}, 1000);},// 带参数且返回 PromisefetchData({ commit }, payload) {return new Promise((resolve, reject) => {axios.get('/api/data', { id: payload.id }).then(response => {commit('SET_DATA', response.data); // 提交 mutation 修改状态resolve(); // 通知调用方操作完成}).catch(error => reject(error));});}
}
触发方式:
组件中通过 dispatch
触发:
// 调用异步 action
this.$store.dispatch('incrementAsync');// 带参数并处理 Promise
this.$store.dispatch('fetchData', { id: 123 }).then(() => console.log("Data loaded!")).catch(err => console.error(err));
应用场景对比
Mutation 的典型场景:
- 简单状态更新:
mutations: {SET_USER(state, user) {state.user = user;} }
- 同步计数/开关:
mutations: {TOGGLE_SIDEBAR(state) {state.isSidebarOpen = !state.isSidebarOpen;} }
Action 的典型场景:
- 异步 API 请求:
actions: {async login({ commit }, credentials) {const user = await api.login(credentials);commit('SET_USER', user); // 提交 mutation} }
- 组合多个操作:
actions: {checkout({ commit, dispatch }, cartItems) {commit('CLEAR_CART'); // 同步清空购物车dispatch('saveOrder', cartItems); // 异步保存订单},saveOrder({ commit }, items) { ... } }
- 条件性提交 mutation:
actions: {updateProfile({ commit, state }, data) {if (state.isLoggedIn) {commit('UPDATE_PROFILE', data);}} }
总结
特性 | Mutation | Action |
---|---|---|
职责 | 直接修改状态 | 调用 mutation + 业务逻辑 |
是否支持异步 | ❌ 必须是同步 | ✔️ 支持异步操作 |
调用方式 | commit('name', payload) | dispatch('name', payload) |
适用场景 | 简单状态更新 | API 请求、复杂逻辑 |
设计原则:
组件 → dispatch
Action → commit
Mutation → 修改 State → 更新视图
通过分离同步(Mutation)和异步(Action)逻辑,Vuex 保证了状态变更的可预测性和可维护性。