Vuex Store 核心概念:state、getters、mutations、actions 详解
Vuex 是 Vue 的集中式状态管理库,用于统一管理 Vue 应用的共享数据。它的核心由 4 个部分组成:state、getters、mutations、actions,各司其职,严格遵循单向数据流规则。
我用最通俗的方式给你讲清楚每个部分的作用、用法和区别。
一、核心总览
| 模块 | 作用 | 特点 | 调用方式 |
|---|---|---|---|
| state | 存储原始数据(数据源) | 唯一数据源,只读 | $store.state.xxx |
| getters | 对 state 数据加工/计算(类似 computed) | 缓存结果,依赖 state | $store.getters.xxx |
| mutations | 同步修改 state(唯一合法修改方式) | 必须同步,直接改数据 | $store.commit('xxx') |
| actions | 异步操作(请求接口、定时器) | 处理异步,不直接改 state,最终提交 mutation | $store.dispatch('xxx') |
二、逐模块详细讲解
1. State:数据源(存数据)
作用:存储 Vuex 中所有的共享原始数据,相当于组件中的 data,但全局共享。
- 所有组件都能访问,是整个应用的唯一数据源。
- 直接修改 state 是不合法的!必须通过 mutations 修改。
示例代码
// store/index.js
const store = new Vuex.Store({
// 存储共享数据
state: {
count: 0,
userInfo: { name: "张三", age: 20 }
}
})
组件中使用
<template>
<div>{{ $store.state.count }}</div>
</template>
2. Getters:计算属性(加工数据)
作用:对 state 中的数据进行计算、过滤、加工,相当于组件中的 computed,全局复用。
- 依赖 state 数据,数据变化时自动更新,且有缓存。
- 适合多个组件需要同一种加工后的数据时使用。
示例代码
const store = new Vuex.Store({
state: {
count: 0,
list: [1, 2, 3, 4, 5]
},
// 加工 state 数据
getters: {
// 计算双倍 count
doubleCount(state) {
return state.count * 2;
},
// 过滤偶数
evenList(state) {
return state.list.filter(item => item % 2 === 0);
}
}
})
组件中使用
<template>
<div>双倍:{{ $store.getters.doubleCount }}</div>
<div>偶数列表:{{ $store.getters.evenList }}</div>
</template>
3. Mutations:同步修改器(改数据)
作用:唯一能修改 state 的地方,且必须是同步操作。
- 修改规则:通过
commit提交 mutation,不能直接调用。 - 必须同步!不能写异步代码(axios、定时器等)。
示例代码
const store = new Vuex.Store({
state: { count: 0 },
// 同步修改 state
mutations: {
// 第一个参数固定是 state,第二个是传入的参数
addCount(state, num) {
state.count += num;
}
}
})
组件中使用(提交修改)
// 触发 mutation
this.$store.commit('addCount', 10);
4. Actions:异步管理器(处理异步)
作用:处理异步操作(接口请求、定时器、延时操作等),不直接修改 state。
- 异步完成后,通过
commit提交 mutation 间接修改 state。 - 组件通过
dispatch触发 actions。
示例代码
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
setCount(state, num) {
state.count = num;
}
},
// 处理异步
actions: {
// 第一个参数固定是 context(包含 commit、state 等)
async getCountFromApi(context) {
// 模拟接口请求(异步)等1秒,拿到 100
//const res = await axios.get('/api/count')
const res = await new Promise(resolve => {
setTimeout(() => resolve(100), 1000); //等1秒,拿到 100
});
// 提交 mutation 修改 state
context.commit('setCount', res);//context.commit('setCount', 100);
}
}
})
组件中使用(触发异步)
// 触发 action
this.$store.dispatch('getCountFromApi');
三、核心执行流程(必背)
这是 Vuex 最核心的数据流,一定要记牢:
- 组件 dispatch 触发 → actions(处理异步)
- actions commit 提交 → mutations(同步改数据)
- mutations 修改 → state(数据源更新)
- state 更新 → 组件重新渲染
一句话总结:
组件调 actions → actions 调 mutations → mutations 改 state → 视图更新
四、快速区分口诀
-
存数据 →
state -
算数据 →
getters -
同步改 →
mutations+commit -
异步改 →
actions+dispatch
总结
- state:存原始数据,唯一数据源;
- getters:加工/计算 state 数据,全局复用;
- mutations:同步修改 state,唯一合法修改方式;
- actions:处理异步操作,提交 mutation 间接改 state。