vuex Module Splitting store into modules

  • 2021-10-13 06:11:56
  • OfStack

Because of the single 1 state tree, all the applied states will be concentrated in one relatively large object. When the application becomes very complex, store objects may become quite bloated.

To solve the above problems, Vuex allows us to divide store into modules (module). Each module has its own state, mutation, action, getter, and even nested sub-modules-split in the same way from top to bottom:


const moduleA = {
 state: () => ({ ... }),
 mutations: { ... },
 actions: { ... },
 getters: { ... }
}
 
const moduleB = {
 state: () => ({ ... }),
 mutations: { ... },
 actions: { ... }
}
 
const store = new Vuex.Store({
 modules: {
 a: moduleA,
 b: moduleB
 }
})
 
store.state.a // -> moduleA  State of 
store.state.b // -> moduleB  State of 

Supplementary knowledge: vuex realizes modular partition and places corresponding data and operations in different types of files

The directory structure is

store folder has index. js, modules folder, modules folder is your module, it is best to name through the function

Level 1 directory: store

Files in Level 1 directory: index. js

Level 2 directory: modules

Level 3 directory demo

File demo. js in Level 3 directory

File getter. js in Level 3 directory

File mutations. js in Level 3 directory

Files state and js under Level 3 directory

The contents of each document are

index. js under level 1 directory


import Vue from 'vue'
import Vuex from 'vuex'
import demo from './modules/demo/demo.js';
Vue.use(Vuex);
const $store = new Vuex.Store({
    modules: {
          demo
    }
});
export default $store;

demo. js under level 3 directory


import state from './state.js';
import mutations from './mutations.js';
//  Import on demand 
// import getters from './getters.js';
// import actions from './actions.js';

export default{
//  Expose the imported file 
 state,
 mutations
}

Level 3 Directory Other Files

export default{}

Finally mounted in main. js


import Vue from 'vue'
import App from './App'
import router from './router'
import { RouterMount } from 'uni-simple-router'
// Introduce vuex
import store from './store'
// Put vuex Define as a global component 
Vue.prototype.$store = store

Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
 store,
  ...App
})
app.$mount();

Related articles: