持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第18天。
简介
Vuex 是专为 VUE 开发的状态管理模式,采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
以下是一个表示“单向数据流”理念的简单示意:
每一个 Vuex 应用的核心就是 store(仓库),并包含这应用中的大部分状态,Vuex 和单纯的全局对象有以下两点不同:
- Vuex 的状态存储是响应式的 2.不能直接改变 store 中的状态
核心概念
state
vuex 使用单一状态树,即一个对象包含了全部的应用层级状态。
读取状态
从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态:
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
getter
有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:
它接受 state 作为其第一个参数
const store = createStore({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos (state) {
return state.todos.filter(todo => todo.done)
}
}
})
我们还可以通过属性访问:
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler) 。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
定义:
const store = createStore({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
调用:
store.commit('increment')
组件中提交:
this.$store.commit('xxx')
注意: mutation 必须是同步函数
action
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
定义:
const store = createStore({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
分发:
store.dispatch('increment')
module
Vuex 允许我们将 store 分割成模块(module) 。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = createStore({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态