於使用單一狀態樹,應用的所有狀態會集中到一個比較大的對象。當應用變得非常復雜時,store 對象就有可能變得相當臃腫。為了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割:
如何使用module
在store文件夾下新建modules文件夾,並在下面建立moduleA.js和moduleB.js文件用來存放vuex的modules模塊
moduleA.js文件內容如下:
const state = { stateA: 'A' } const mutations = { showA (state) { return state.stateA } } const actions = { showAAction (context) { context.commit('showA') } } const getters = { getA (state) { return state.stateA } } export default {state, mutations, actions, getters}
moduleB.js文件內容如下:
const state = { stateB: 'B' } const mutations = { showA (state) { return state.stateB } } const actions = { showAAction (context) { context.commit('showB') } } const getters = { getA (state) { return state.stateB } } export default {state, mutations, actions, getters}
store.js 文件內容如下:
import Vue from 'vue' import Vuex from 'vuex' import state from './state' import mutations from './mutations' import getters from './getters' import actions from './actions' import moduleA from './modules/moduleA' import moduleB from './modules/moduleB' Vue.use(Vuex) const store = new Vuex.Store({ state, mutations, getters, actions, modules: { moduleA, moduleB } export default store
在組件中使用
<template> <div class="modules"> <h1>{{moduleA}} --- {{moduleB}}</h1> </div> </template> <script> import { mapState } from 'vuex' export default { data () { return {} }, computed: { ...mapState({ moduleA: state => state.moduleA.stateA, moduleB: state => state.moduleB.stateB }) } } </script>
模塊動態注冊
在 store 創建之后,你可以使用 store.registerModule 方法注冊模塊:
// 注冊模塊 `myModule` store.registerModule('myModule', { // ... }) // 注冊嵌套模塊 `nested/myModule` store.registerModule(['nested', 'myModule'], { // ... })
之后就可以通過 store.state.myModule 和 store.state.nested.myModule 訪問模塊的狀態。模塊動態注冊功能使得其他 Vue 插件可以通過在 store 中附加新模塊的方式來使用 Vuex 管理狀態。例如,vuex-router-sync 插件就是通過動態注冊模塊將 vue-router 和 vuex 結合在一起,實現應用的路由狀態管理。你也可以使用 store.unregisterModule(moduleName) 來動態卸載模塊。注意,你不能使用此方法卸載靜態模塊(即創建 store 時聲明的模塊)。