VUEX
![在这里插入图片描述](https://img-blog.csdnimg.cn/f4e56a99b2c5495c88a72f54aefd766c.png)
state.js
const state = {
addRouters: undefined,
topNavigation: undefined,
leftNavigation: undefined,
}
export default state
getters.js
const getters = {
addRoutersPath: (state) => {
return state.addRouters.filter(item=> item.path)
}
}
export default getters
mutations.js
SET_ADD_ROUTERS: (state, data) => {
state.addRouters = data
},
SET_USE_RSET: (state, data) => {
state.userSet = data
},
SET_TOP_NAVIGATION: (state, data) => {
state.topNavigation = data
},
SET_LEFT_NAVIGATION: (state, data) => {
state.leftNavigation = data
},
actions.js
import { getUserInfo } from "api/index";
import { generateIndexRouter, getTopNavigation } from "@/utils/util";
import router from "@/router";
const actions = {
callUserInfor({ commit }) {
return new Promise((resolve, reject) => {
getUserInfo()
.then(res => {
if (JSON.stringify(res.data) !== "{}" && JSON.stringify(res.data) !== "[]") {
const menu = generateIndexRouter(res.data?.menu)
window.sessionStorage.setItem("menu",
JSON.stringify(res?.data?.menu))
commit("SET_ADD_ROUTERS", menu);
const header = getTopNavigation(res.data?.menu)
window.sessionStorage.setItem("head", JSON.stringify(header));
commit("SET_TOP_NAVIGATION", header);
router.selfaddRoutes(menu);
} else {
commit("SET_ADD_ROUTERS", undefined);
commit("SET_TOP_NAVIGATION", undefined);
}
resolve(res);
})
.catch(error => {
reject(error);
});
});
}
};
export default actions;
router.js
import store from "../store";
const createRouter = () => new VueRouter({
mode: "hash",
routes: constantRouterMap
});
const router = createRouter();
router.selfaddRoutes = params => {
const newRouter = createRouter();
router.matcher = newRouter.matcher;
if (params) {
router.addRoute(params);
}
router.history.setupListeners()
};
router.beforeEach((to, from, next) => {
if (store.state.topNavigation) {
next();
} else {
store.dispatch("callUserInfor").then(() => {
const name = window.localStorage.getItem("name");
let left;
const { topNavigation } = store.state;
if (name !== "工作空间" && topNavigation) {
left = topNavigation.filter(item => item.name === name)[0].left;
}
store.commit("SET_LEFT_NAVIGATION", left);
next({
path: to.fullPath
});
});
}
)}