Vuex 是 Vue 的官方状态管理库,用于管理应用中的共享状态。它的核心概念包括 state、getter、mutation、action 和 module,每个概念都有其特定的作用。以下是它们的详细说明:
1. State
- 作用:存储应用的状态(数据)。
- 特点:
- 状态是响应式的,状态变化会自动更新视图。
- 状态是唯一的,存储在全局的
state
对象中。
- 示例:
const store = new Vuex.Store({
state: {
count: 0,
},
});
2. Getter
- 作用:从
state
中派生出计算属性。 - 特点:
- 类似于 Vue 组件中的
computed
,具有缓存机制。 - 可以接收其他
getter
作为第二个参数。
- 类似于 Vue 组件中的
- 示例:
const store = new Vuex.Store({
state: {
count: 0,
},
getters: {
doubleCount: (state) => state.count * 2,
},
});
3. Mutation
- 作用:修改
state
的唯一方式。 - 特点:
- 必须是同步函数。
- 通过
commit
方法触发。 - 每个
mutation
都有一个字符串类型的事件类型(type)和一个回调函数(handler)。
- 示例:
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
});
// 触发 mutation
store.commit('increment');
4. Action
- 作用:处理异步操作,并提交
mutation
来修改state
。 - 特点:
- 可以包含任意异步操作。
- 通过
dispatch
方法触发。 - 不能直接修改
state
,必须通过提交mutation
来修改。
- 示例:
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
},
},
});
// 触发 action
store.dispatch('incrementAsync');
5. Module
- 作用:将
store
分割成模块,每个模块拥有自己的state
、getter
、mutation
和action
。 - 特点:
- 适合大型项目,避免
store
变得臃肿。 - 模块可以嵌套。
- 适合大型项目,避免
- 示例:
const moduleA = {
state: { count: 0 },
mutations: {
increment(state) {
state.count++;
},
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
},
},
getters: {
doubleCount: (state) => state.count * 2,
},
};
const store = new Vuex.Store({
modules: {
a: moduleA,
},
});
// 访问模块中的 state
console.log(store.state.a.count); // 0
总结
概念 | 作用 | 特点 |
---|---|---|
State | 存储应用的状态 | 响应式,全局唯一 |
Getter | 从 state 中派生出计算属性 | 类似于 computed ,具有缓存机制 |
Mutation | 修改 state 的唯一方式 | 必须是同步函数,通过 commit 触发 |
Action | 处理异步操作,提交 mutation | 可以包含异步操作,通过 dispatch 触发 |
Module | 将 store 分割成模块 | 适合大型项目,避免 store 臃肿 |
使用场景
- State:存储全局共享的数据。
- Getter:从
state
中派生出复杂的数据。 - Mutation:同步修改
state
。 - Action:处理异步操作(如 API 请求),并提交
mutation
。 - Module:组织大型应用的状态管理逻辑。
通过合理使用这些概念,可以构建出清晰、可维护的状态管理架构。
THE END
暂无评论内容