Vuex基础指南

89 阅读7分钟
  • 为 vue 专门设计的一套状态管理库,利用 vue 细粒度数据响应机制来进行高效的状态更新
  • 全局性的状态管理器,通过强制规则维持视图和状态间的独立性

State

  • 唯一数据源
  • 一个对象包含全部的应用级状态

读取 store 数据

  • 由于 vuex 中的数据是响应式的,最简单的方式是通过 computed 读取

全局注入

  • vuex 通过 store 选项,提供一种机制将状态从根组件注入到每个子组件
  • 需要全局注入
const app = new Vue({
    el: "#app",
    // 把 store 对象提供给 "store" 选项,这可以吧 store 的实例注入所有的子组件
    store,
    template: `<div class="app">
        <counter></counter>
    </div>`
})

mapState 辅助函数

  • 当一个组件需要获取多个状态时,可以利用 mapState 帮助生成计算属性
// 在单独构建的版本中,辅助函数为 Vuex.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
        }
    })
}
  • 当映射的计算属性名称与 state 子节点名称相同时,可以给 mapState 传一个数组
computed: mapState([
    // 映射 this.count 为 store.state.count
    'count'
])

对象展开运算符

  • mapState 函数返回的是一个对象,使用对象展开运算符,将 mapState 函数返回的数据混入到局部计算属性中
computed: {
    localComputed() {
        // 使用对象展开运算符将此对象混入到外部对象中
        ...mapState({ ... })
    }
}

Getter

  • getter 的返回值回根据它的依赖缓存起来,且只有它依赖的缓存值发生改变才会被重新计算
  • 相当于 store 的计算属性

可接收参数:state 作为第一个参数,getter第二个参数

getters: {
    doneTodos: state => {
        return state.todos.filter(todo => todo.done)
    }
}
getters: {
    doneTodos: (state, getters) => {
        return getters.doneTodos.length
    }
}

通过属性访问

  • getters 会暴露 store.getters 对象,可以以属性的形式访问
  • getters 在通过属性访问时,每次都会进行调用,而不会缓存结果
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

我们可以很容易的在任务组件中使用它

computed: {
    doneTodosCount() {
        return this.$store.getters.doneTodosCount
    }
}

mapGetters 辅助函数

  • 仅仅是将 store 中的 getter 映射到局部的计算属性
import { mapGetters } from 'vuex'

export default {
    computed: {
        ...mapGetters([
            'doneTodosCount',
            'anotherGetter',
            ...
        ])
    }
}
  • 可以将 getter 属性设置另一个名字
...mapGetters({
    //`this.doneCount` 映射到 `this.$store.getters.doneTodoCount`
    doneCount: 'doneTodosCount'
})

Mutation

更改vuex的store的状态的唯一方法是提交mutation

  • 类似于事件,每个 mutation 都有一个字符串类型和一个回调哈书,这个回调函数就是实际进行状态更改的点个,并会接受 state 为第一个参数
const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

Mutation 必须是同步函数

  • mutation 必须是同步函数
  • 任何回调函数中进行的状态改变都是不可追踪的,加入在debug状态下,要取到每一条 mutation 记录的前一状态和后一状态,如果 mutation 是异步函数,当 mutation 触发时,不能保证回调函数被调用,所以对捕捉状态会有影响。

在组件中提交 mutation

  • 可以在组件中使用 this.$store.commit('xxxx') 提交
  • 可以使用 mapMutation 辅助函数,将组件中的 methods 映射到 store.commit 调用
import { mapMutaion } 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 可以包含任何异步操作
  • 注册简单的 Action 示例
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})
  • Action 接收一个与 store 实例相同方法和属性的 context 对象,因此可以调用 context.commit 调用一个 mutation 。活着通过 context.state 或 context.getters 获取 state 和 getters

  • 实践中,常用 ES6 的参数结构简化代码, 特别是需要调用 commit 多次的时候

分发 Action

  • action 通过 dispatch 方法触发
store.dispatch('increment')
  • 可以在 action 中执行异步
actions: {
    incrementAsync: ({ commit }) {
        setTimeout((() => {
            commit('increment')
        })
    }
}
  • Action 也支持载荷方式和对象方式
store.dispatch('incrementAsync', {
    count: 0
})
store.dispatch({
    type: 'incrementAsync',
    count: 10
})

在组件中分发 Action

  • 在组件中使用 this.$store.dispatch('xxx') 或 mapAction 将组件中的 methods 映射到 store.dispatch 调用
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

  • store.dispatch 可以处理被触发的 action 返回的 Promise,并且 store.dispatch 仍然返回 Promise
actions: {
    actionA: ({ commit }) {
        return new Promise(( resolve, reject ) => {
            setTimeout(() => {
                commit('someMutation');
                resolve()
            }, 1000)
        })
    }
}
  • 现在可以这样用
store.dispatch('actionA').then(() => {})
  • 在另外一个 action 中使用也可以
actions: {
    actionB: ({dispatch, commit}) {
        return dispatch('actionA').then(() => {
            commit('someMutation')
        })
    }
}
  • 也可以利用 async/await 组合 action
// 假设 getData 和  getOtherData 返回的都是 Promise

actions: {
   async actionA: ({ commit }) {
       commit('gotData', await getData())
   },
   async actionB: ({ dispatch, commit }) {
       await dispatch('actionA') // 等待 actionA 执行完成
       commit('gotOtherData', await getOtherData)
   }
}
  • 一个 store.dispatch 在不同模块中可以触发多个 action 。在这种情况下,只有当触发函数完成后,返回的 Promise 才会执行

Module

  • 当使用单一状态树,应用的所有模块都集中在一个比较大的对象,当业务模块比较复杂,store 对象就会变得很臃肿,增加了维护难度
  • 为了解决上述问题,vuex 允许我们将 store 分割成模块(Module)。每个模块拥有自己的 state、,mutation、action、getter。甚至是嵌套子模块,从上到下的分割模块
// moduleA
const moduleA = {
    state: () => {},
    actions: {},
    mutation: {},
    getters: {}
}

// moduleB
const moduleB = {
    state: () => {},
    actions: {},
    mutation: {},
    getters: {}
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

模块的局部状态

  • 对于模块内部的 mutation 和 getters,接收的是模块的局部对象
const moduleA = {
  state: () => ({
    count: 0
  }),
  mutations: {
    increment (state) {
      // 这里的 `state` 对象是模块的局部状态
      state.count++
    }
  },

  getters: {
    doubleCount (state) {
      return state.count * 2
    }
  }
}
  • 对于局部内部的 action ,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState
const moduleA = {
  // ...
  actions: {
    incrementIfOddOnRootSum ({ state, commit, rootState }) {
      if ((state.count + rootState.count) % 2 === 1) {
        commit('increment')
      }
    }
  }
}
  • 对于模块内部的 getters,根节点状态会作为第三个参数暴露出来
const moduleA = {
  // ...
  getters: {
    sumWithRootCount (state, getters, rootState) {
      return state.count + rootState.count
    }
  }
}

命名空间

  • 默认情况下,模块内部的 action、mutation、getter 是注册在全局命名空间的,这样可以多个模块对统一 mutation 或 action 做出响应
  • 如果希望模块有高封装和高复用,可以通过添加 namespaced: true 使其成为带命名空间的模块,当模块被注册后,它的所有 getter、mutation 和 action 都会自动根据模块注册的命名空间调整命名
const store = new Vuex.Store({
  modules: {
    account: {
      namespaced: true,

      // 模块内容(module assets)
      state: () => ({ ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },

      // 嵌套模块
      modules: {
        // 继承父模块的命名空间
        myPage: {
          state: () => ({ ... }),
          getters: {
            profile () { ... } // -> getters['account/profile']
          }
        },

        // 进一步嵌套命名空间
        posts: {
          namespaced: true,

          state: () => ({ ... }),
          getters: {
            popular () { ... } // -> getters['account/posts/popular']
          }
        }
      }
    }
  }
})
  • 启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit。换言之,你在使用模块内容(module assets)时不需要再同一模块内额外添加空间名前缀。更改 namespaced 属性后不需要修改模块内的代码

在带命名空间的模块内访问全局内容(Global Assets)

  • 如果你希望使用全局 state 和 getter,rootState 和 rootGetters 会作为第三和第四参数传入Getter。也会通过 context 对象的属性传入 action
  • 若需要在 全局命名空间内 分发 action 或 提交mutation,将 root:true 作为第三个参数传给 dispatch或commit 即可。
modules: {
  foo: {
    namespaced: true,

    getters: {
      // 在这个模块的 getter 中,`getters` 被局部化了
      // 你可以使用 getter 的第四个参数来调用 `rootGetters`
      someGetter (state, getters, rootState, rootGetters) {
        getters.someOtherGetter // -> 'foo/someOtherGetter'
        rootGetters.someOtherGetter // -> 'someOtherGetter'
      },
      someOtherGetter: state => { ... }
    },

    actions: {
      // 在这个模块中, dispatch 和 commit 也被局部化了
      // 他们可以接受 `root` 属性以访问根 dispatch 或 commit
      someAction ({ dispatch, commit, getters, rootGetters }) {
        getters.someGetter // -> 'foo/someGetter'
        rootGetters.someGetter // -> 'someGetter'

        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'

        commit('someMutation') // -> 'foo/someMutation'
        commit('someMutation', null, { root: true }) // -> 'someMutation'
      },
      someOtherAction (ctx, payload) { ... }
    }
  }
}

在带命名空间的模块注册全局 action

  • 若需要在带命名空间的模块注册全局 action,可以添加 root:true,并将这个 action 的定义放在函数 handler 中
{
  actions: {
    someOtherAction ({dispatch}) {
      dispatch('someAction')
    }
  },
  modules: {
    foo: {
      namespaced: true,

      actions: {
        someAction: {
          root: true,
          handler (namespacedContext, payload) { ... } // -> 'someAction'
        }
      }
    }
  }
}

带命名空间的绑定函数

  • 当使用 mapState,mapGetters mapActions mapMutations 这些函数来绑定带命名空间的模块时,写起来比较繁琐,例如:
computed: {
  ...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  })
},
methods: {
  ...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    'some/nested/module/bar' // -> this['some/nested/module/bar']()
  ])
}
  • 对于这种情况,可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。于是可以把上面的例子简化为:
computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  })
},
methods: {
  ...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
  ])
}
  • 而且,还可以通过使用 createNamespacedHelpers 创建基于某个命名空间的辅助函数,它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数
import { createNamespacedHelpers } from 'vuex'

const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')

export default {
  computed: {
    // 在 `some/nested/module` 中查找
    ...mapState({
      a: state => state.a,
      b: state => state.b
    })
  },
  methods: {
    // 在 `some/nested/module` 中查找
    ...mapActions([
      'foo',
      'bar'
    ])
  }
}