[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的用法(終篇)

相關文章
相關標籤/搜索