Skip to content

Vuex 基础 ​

Vuex 是 Vue 的状态管理库,集中存储管理所有组件的公共数据,主要用于跨组件的通信。

每个 Vuex 应用的核心是 store(仓库),store 中核心概念有 5 个:

  • state:存储整个应用的所有状态,相当于组件的 data。
  • getters:相当于 store 的计算属性。
  • mutations:修改 state 的唯一途径。
  • actions:类似于 mutations,不过是用于处理异步操作和复杂的业务逻辑。
  • modules:用于将 store 分割成模块。

Vuex 3.x 只适配 Vue 2,而 Vuex 4.x 适配 Vue 3。

Store ​

每个应用仅有一个 store 实例。

js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({  
  state: {},  
  getters: {},  
  mutations: {},  
  actions: {}  
})  

new Vue({
  el: '#app',  
  store // 根实例注入store后,组件中可直接this.$store来使用  
})

State ​

store 的 state 相当于所有组件的 data,保存着所有组件的公共数据。

展示 state 状态的最简单方法是用计算属性。

js
export default {  
  computed: {  
    count() {
      return this.$store.state.count  
    }
  }
}

mapState ​

mapState 辅助函数用于便捷地把 state 状态生成组件的计算属性。

js
import { mapState } from 'vuex'

export default {  
  computed: mapState({  
    // 第一个参数会是state
    count: state => state.count,
    // 起别名
    countAlias: 'count'
  })  
}

如果计算属性的名称和 state 里的属性名相同,可传一个字符串数组。

js
export default {
  computed: {
    ...mapState(['count'])
  }
}

Getters ​

getters 相当于 store 的计算属性,也会缓存 getter 的返回值。

js
new Vuex.Store({
  state: {
    todos: []
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    },
    doneTodosCount: (state, getters) => {
      return getters.doneTodos.length
    }
  }
})

组件中通过 this.$store.getters 对象来访问这些值。

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

mapGetters ​

mapGetters 辅助函数可便捷地将 store 中 getter 映射到组件的计算属性,使用方式跟 mapState 一样。

js
import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters(['doneTodosCount', 'anotherGetter'])
  }
}

Mutations ​

修改 store 中状态的唯一方法是提交 mutation,mutation 方法的第一个参数会是 state,第二个为自定义传来的参数 payload,payload 建议是一个对象。

注意 mutation 里的代码必须是同步的。

js
new Vuex.Store({
  mutations: {
    increment(state, payload) {
      state.count++
    }
  }
})

mapMutation ​

组件中通过 this.$store.commit('xxx') 来提交 mutation,或使用 mapMutations 辅助函数将 mutation 映射到组件的 methods 里,这样就可直接通过 this 来调用。

js
import { mapMutations } from 'vuex'

export default {
  methods: {
    ...mapMutations(['increment'])
  }
}

Actions ​

action 提交的是 mutation,而不是直接修改 state 状态,action 通常包含异步操作。

action 方法第一个参数为 context,其与 store 实例具有相同属性和方法,所以可访问 context.state 和 context.getters。

js
new Vuex.Store({
  actions: {
    increment(context) {
      context.commit('increment')
    }
  }
})

mapActions ​

组件中可直接 this.$store.dispatch('xxx') 来触发 action 方法,也可使用 mapActions 辅助函数将 action 方法映射到组件 methods 中,这样就可直接 通过 this 来调用。

js
import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions(['increment', 'incrementBy'])
  }
}

组合 action ​

action 中可返回 Promise,来按顺序执行一系列异步操作,通过 dispatch 方法触发,不直接修改 state,而是提交 mutations。

js
new Vuex.Store({
  actions: {
    async actionA ({ commit }) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          commit('someMutation')
          resolve()
        }, 1000)
      })
    },
    async actionB ({ dispatch, commit }) {
      await dispatch('actionA') // 等待actionA完成  
      commit('gotOtherData', await getOtherData())
    }
  }
})

Modules ​

所有组件的公共数据都会保存在一个大对象中,这不方便维护,所以 Vuex 允许将 store 分割为模块,每个模块有自己的 state、mutations、actions 和 getters。

js
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的状态

模块局部状态 ​

模块中的 state、mutations、actions 和 getters 都是独立互不影响的,mutation 和 getter 的第一个参数是当前模块的 state,如果要访问根节点状态,可使用 rootState。

js
const moduleA = {
  getters: {
    doubleCount (state, getters, rootState) {}
  },
  actions: {
    increment({ state, commit, rootState }) {}
  }
}

命名空间 ​

默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间,这可让多个模块能对同一 mutation 或 action 作出响应。

可通过添加 namespaced: true 来使用命名空间。

js
new Vuex.Store({
  modules: {
    account: {
      namespaced: true,
      state: () => ({}),
      getters: {
        // getters['account/isAdmin']
        isAdmin() {}
      },
      actions: {
        // dispatch('account/login')
        login () {}
      },
      mutations: {
        // commit('account/login')
        login () {}
      }
    }
  }
})

带命名空间的绑定函数 ​

使用 mapState、mapGetters、mapActions 和 mapMutations 辅助函数时,如果带有命名空间,有简洁的写法。

空间名称作为第一个参数,这样所有绑定都会自动将该模块作为上下文。

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

createNamespacedHelpers ​

可使用 createNamespacedHelpers 函数创建基于某个命名空间的辅助函数。

js
import { createNamespacedHelpers } from 'vuex'

const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
export default {
  computed: {
    ...mapState({
      a: state => state.a,
      b: state => state.b
    })
  },
  methods: {
    ...mapActions(['foo', 'bar'])
  }
}