Router Modules模块化

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
例如:在我的一个项目中,我单独为导航栏菜单建立了一个模块,文件名为menu.js,所以我的store结构图如下
在这里插入图片描述

store index.js 中两步设置
1:导入导航栏子模块import menus from ‘…/store/modules/menu’
2:在modules中引用menus

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
注意:
错误写法:export default new Vuex.Store({})
正确写法:export default{} ,因为Store只能有一个,并且放在store下的index.js,所以我们menu只是返回一个对象
记得在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: {
    },
}

引用子模块变量
以menu.js中menuList变量为例

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

猜你喜欢

转载自blog.csdn.net/weixin_43424325/article/details/121333108