VUEX文档阅读摘要
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
State
单一状态树,
由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态
// 创建一个 Counter 组件const Counter = { template: `<div>{{ count }}</div>`, computed: { count () { return store.state.count } }}
mapState 辅助函数
import { mapState } from 'vuex' export default { // ... computed: mapState({ // 箭头函数可使代码更简练 count: state => state.count, // 传字符串参数 'count' 等同于 `state => state.count` countAlias: 'count', // 为了能够使用 `this` 获取局部状态,必须使用常规函数 countPlusLocalState (state) { return state.count + this.localCount } }) } // 映射 this.count 为 store.state.count computed: mapState(['count']) // 将它与局部计算属性混合使用,对象展开运算符 computed: { localComputed () { /* ... */ }, // 使用对象展开运算符将此对象混入到外部对象中 ...mapState({ // ... })}
Getter
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } }}) // Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值: store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }] // Getter 也可以接受其他 getter 作为第二个参数 getters: { // ... doneTodosCount: (state, getters) => { return getters.doneTodos.length }} // 在任何组件中使用 computed: { doneTodosCount () { return this.$store.getters.doneTodosCount }} // 让 getter 返回一个函数,来实现给 getter 传参 getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) }}
mapGetters 辅助函数
import { mapGetters } from 'vuex'export default { // ... computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) }} mapGetters({ // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount` doneCount: 'doneTodosCount' })
Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
mutation 必须是同步函数
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state, n) { // 变更状态 state.count += n } }}) // 要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法 store.commit('increment', 2)
你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)
import { mapMutations } from 'vuex'export default { // ... methods: { ...mapMutations([ 'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')` // `mapMutations` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)` ]), ...mapMutations({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')` }) }}
Action
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } }}) // 我们会经常用到 ES2015 的 参数解构 来简化代码 actions: { increment ({ commit }) { commit('increment') }}
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
分发 Action
Action 通过 store.dispatch 方法触发
store.dispatch('increment') // 以载荷形式分发 store.dispatch('incrementAsync', { amount: 10 }) // 以对象形式分发store.dispatch({ type: 'incrementAsync', amount: 10 })
在组件中分发 Action
组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用
mapActions 辅助函数
import { mapActions } from 'vuex' export default { // ... methods: { ...mapActions([ 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')` // `mapActions` 也支持载荷: 'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)` ]), ...mapActions({ add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')` }) }}
组合 Action
actions: { // ... actionB ({ dispatch, commit }) { return dispatch('actionA').then(() => { commit('someOtherMutation') }) } } 利用 async / await,我们可以如下组合 action // 假设 getData() 和 getOtherData() 返回的是 Promiseactions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ({ dispatch, commit }) { await dispatch('actionA') // 等待 actionA 完成 commit('gotOtherData', await getOtherData()) }}
Module
Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } }) store.state.a // -> moduleA 的状态 store.state.b // -> moduleB 的状态
对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象
同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState
对于模块内部的 getter,根节点状态会作为第三个参数暴露出来
const moduleA = { // ... actions: { incrementIfOddOnRootSum ({ state, commit, rootState }) { if ((state.count + rootState.count) % 2 === 1) { commit('increment') } } }} const moduleA = { // ... getters: { sumWithRootCount (state, getters, rootState) { return state.count + rootState.count } }}
命名空间
模块动态注册
在 store 创建之后,你可以使用 store.registerModule 方法注册模块
// 注册模块 `myModule` store.registerModule('myModule', { // ... }) // 注册嵌套模块 `nested/myModule` store.registerModule(['nested', 'myModule'], { // ... })
应用层级的状态应该集中到单个 store 对象中。
提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。
异步逻辑都应该封装到 action 里面。
参与讨论