因爲使用單一狀態樹,應用的全部狀態會集中到一個比較大的對象。當應用變得很是複雜時,store 對象就有可能變得至關臃腫。javascript
爲了解決以上問題,Vuex 容許咱們將 store 分割成模塊(module)。每一個模塊擁有本身的 state、mutation、action、getter。html
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const moduleA = { state: { countA: 0 }, getters: { totalA: (state) => (symbol) => { return (symbol || '$') + state.countA } }, mutations: { incrementA(state, payload){ state.countA += (payload || 1); } } } const moduleB = { state: { countB: 0 }, getters: { totalB: (state) => (symbol) => { return (symbol || '$') + state.count } }, mutations: { incrementB(state, payload){ state.countB += (payload || 1); } } } const store = new Vuex.Store({ modules: { moduleA, moduleB } }) export default store
<input type="button" value="increment" @click="add()"/> <span>{{countA}}</span> <script> import {mapState, mapMutations, mapActions} from 'vuex'; export default { methods: { ...mapMutations(['incrementA']), ...mapMutations({add: 'incrementA'}) }, computed: { ...mapState({ countA: state => state.moduleA.countA }) } } </script>
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const moduleA = { namespaced: true, state: { count: 0 }, getters: { total: (state) => (symbol) => { return (symbol || '$') + state.count } }, mutations: { increment(state, payload){ state.count += (payload || 1); } } } const moduleB = { namespaced: true, state: { count: 0 }, getters: { total: (state) => (symbol) => { return (symbol || '$') + state.count } }, mutations: { increment(state, payload){ state.count += (payload || 1); } } } const store = new Vuex.Store({ modules: { moduleA, moduleB } }) export default store
methods: { ...mapMutations(['moduleA/increment']), ...mapMutations({add: 'moduleA/increment'}) }, computed: { ...mapState({ countA: state => state.moduleA.count }) }