Router Modulesmodular

Due to the use of a single state tree, all the state of the application will be aggregated into a relatively large object. When the application becomes very complex, the store object has the potential to become quite bloated.
To solve the above problems, Vuex allows us to split the store into modules. Each module has its own state, mutation, action, getter, and even nested submodules - split in the same way from top to bottom:
for example: in one of my projects, I created a separate navigation bar menu Module, the file name is menu.js, so my store structure diagram is as follows
insert image description here

Two-step setup in store index.js
1: Import the navigation bar submodule import menus from '…/store/modules/menu'
2: Reference menus in modules

import Vue from 'vue'
import Vuex from 'vuex'
//导入子模块
import menus from '../store/modules/menu'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: ''
  },
  //异步操作state中的变量
  mutations: {

    //将token放入store,并且存储再localStorage
    SET_TOKEN: (state,token) => {
      //mutations中函数会有两个参数:1:state(固定参数,指state),2:其他参数(可以是传过来的数据)
      //这里只能写state,不能写this.state,否则会报错
      state.token = token;
      localStorage.setItem("token",token);
    },
    //logout清除用户信息
    resetState:  (state) => {
      state.token = '';
    }
  },
  actions: {
  },
  modules: {
    //引用导航栏子模块
    menus,
  }
})

menu.js
Note:
Wrong writing : export default new Vuex.Store({})
Correct writing : export default{}, because there can only be one Store, and it is placed in index.js under store, so our menu just returns an object
Remember to reference the module in index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
//错误写法export default new Vuex.Store({})
//正确写法export default{} ,因为Store只能有一个,并且放在store下的index.js
//记得在index.js中引用该模块
export default {
    state: {
        menuList: [],
        permList: [],//权限列表
    },
    //异步操作state中的变量
    mutations: {
        setMenuList(state,menuList){
            state.menuList = menuList;
        },
        setPermList(state,permList){
            state.permList = permList;
        }
     },
    actions: {
    },
}

Reference submodule variables
Take the menuList variable in menu.js as an example

///导入store
import store from '../store'
//引用menuList
store.state.menus.menuList

Guess you like

Origin blog.csdn.net/weixin_43424325/article/details/121333108