[Vuex系列] - Module的用法(终篇)

因为使用单一状态树,应用的全部状态会集中到一个比较大的对象。当应用变得很是复杂时,store 对象就有可能变得至关臃肿。为了解决以上问题,Vuex 容许咱们将 store 分割成模块(module)。每一个模块拥有本身的state、mutation、action、getter、甚至是嵌套子模块——从上至下进行一样方式的分割:vue

如何使用module

在store文件夹下新建modules文件夹,并在下面创建moduleA.js和moduleB.js文件用来存放vuex的modules模块vue-router

moduleA.js文件内容以下:vuex

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文件内容以下:bash

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 文件内容以下:post

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

复制代码

在组件中使用ui

<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 方法注册模块:spa

// 注册模块 `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 时声明的模块)。插件


1、[Vuex系列] - 初尝Vuex第一个例子code

2、[Vuex系列] - 细说state的几种用法router

3、[Vuex系列] - Mutation的具体用法

4、[Vuex系列] - getters的用法

5、[Vuex系列] - Actions的理解之我见

6、[Vuex系列] - Module的用法(终篇)

相关文章
相关标签/搜索