Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
基本状态管理模式
以下是一个简单的计数应用:
new Vue({// statedata () {return {count: 0}},// viewtemplate: `<div>{{ count }}</div>`,// actionsmethods: {increment () {this.count++}}})
其中:
- state: 驱动应用的数据源
- view: 以声明方式将 state 映射到视图
- actions: 响应在 view 上的用户输入导致的状态变化
基本的状态管理模式是一个单向数据流,但是,当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:
- 多个视图依赖于同一状态
- 来自不同视图的行为需要变更同一状态
这时候,可以把组件的共享状态抽取出来,在一个全局的单例模式下进行管理
Vuex 存储结构
const state = {}// gettersconst getters = {}// actionsconst actions = {}// mutationsconst mutations = {}export default {namespaced: false,state,getters,actions,mutations}
接着统一在 index.js 中进行管理
import Vue from 'vue'import Vuex from 'vuex'import ChildMod from './modules/ChildMod'Vue.use(Vuex)const debug = process.env.NODE_ENV !== 'production'export default new Vuex.Store({modules: {ChildMod,},strict: debug,})
State
即单一状态树, 用一个对象就包含了全部的应用层级状态
store
const store = new Vuex.Store({state: {count: 1},})
基本用法
const Counter = {template: `<div>{{ count }}</div>`,computed: {count () {return this.$store.state.count}}}
mapState 辅助函数用法
在 computed 中使用
// 在单独构建的版本中辅助函数为 Vuex.mapStateimport { 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}})}
使用对象展开运算符写法
computed: {localComputed () { /* ... */ },// 使用对象展开运算符将此对象混入到外部对象中...mapState({// ...})}
Getters
有时候我们需要从 store 中的 state 中派生出一些状态
store
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)},doneTodosCount: (state, getters) => {return getters.doneTodos.length},getTodoById: (state) => (id) => {return state.todos.find(todo => todo.id === id)}}})
基本用法
computed: {doneTodosCount () {return this.$store.getters.doneTodosCount}}
通过方法访问,getter 返回一个函数
// -> { id: 2, text: '...', done: false }this.$store.getters.getTodoById(2)
mapGetters 辅助函数用法
在 computed 中使用
import { mapGetters } from 'vuex'export default {// ...computed: {// 使用对象展开运算符将 getter 混入 computed 对象中...mapGetters(['doneTodosCount','anotherGetter',// ...])}}
如果你想将一个 getter 属性另取一个名字,使用对象形式:
mapGetters({// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`doneCount: 'doneTodosCount'})
Mutations
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
PS: Mutation 必须是同步函数
store
const store = new Vuex.Store({state: {count: 1},mutations: {increment (state, payload) {// 变更状态state.count += payload.amount}}})
基本用法
this.$store.commit('increment', {amount: 10})
对象风格提交方式
this.$store.commit({type: 'increment',amount: 10})
mapMutations 辅助函数用法
在 methods 中使用
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')`})}}
Actions
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态
- Action 可以包含任意异步操作
store
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,但不是 store 实例本身
const store = new Vuex.Store({state: {count: 0},mutations: {increment (state, payload) {state.count += payload.amount}},actions: {increment (context) {context.commit('increment')},incrementAsync ({ commit }, payload) {setTimeout(() => {commit('increment', payload)}, 1000)}}})
基本用法
// 基础分发方式this.$store.dispatch('increment')// 以载荷形式分发this.$store.dispatch('incrementAsync', {amount: 10})// 以对象形式分发this.$store.dispatch({type: 'incrementAsync',amount: 10})
mapActions 辅助函数用法
在 methods 中使用
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')`})}}
回调方式用法
store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise。因此可以这么用:
store.dispatch('actionA').then(() => {// ...})
Module
Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
