因为使用单一状态树,应用的全部状态会集中到一个比较大的对象。当应用变得很是复杂时,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 }) }