Files
pqs-9100_client/frontend/src/routers/modules/dynamicRouter.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-08-22 11:27:06 +08:00
import router from "@/routers/index";
import { LOGIN_URL } from "@/config";
import { RouteRecordRaw } from "vue-router";
import { ElNotification } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import { useAuthStore } from "@/stores/modules/auth";
// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/*.vue");
/**
* @description
*/
export const initDynamicRouter = async () => {
const userStore = useUserStore();
const authStore = useAuthStore();
try {
// 1.获取菜单列表 && 按钮权限列表
await authStore.getAuthMenuList();
await authStore.getAuthButtonList();
// 2.判断当前用户有没有菜单权限
if (!authStore.authMenuListGet.length) {
ElNotification({
title: "无权限访问",
message: "当前账号无任何菜单权限,请联系系统管理员!",
type: "warning",
duration: 3000
});
2025-02-07 10:39:30 +08:00
userStore.setAccessToken("");
userStore.setRefreshToken("");
2025-04-14 14:43:29 +08:00
userStore.setExp(0)
2024-08-22 11:27:06 +08:00
router.replace(LOGIN_URL);
return Promise.reject("No permission");
}
// 3.添加动态路由
authStore.flatMenuListGet.forEach(item => {
item.children && delete item.children;
2025-01-14 11:43:35 +08:00
2024-08-22 11:27:06 +08:00
if (item.component && typeof item.component == "string") {
item.component = modules["/src/views" + item.component + ".vue"];
}
2025-03-07 10:17:06 +08:00
2024-08-22 11:27:06 +08:00
if (item.meta.isFull) {
router.addRoute(item as unknown as RouteRecordRaw);
} else {
router.addRoute("layout", item as unknown as RouteRecordRaw);
}
});
} catch (error) {
// 当按钮 || 菜单请求出错时,重定向到登陆页
2025-02-07 10:39:30 +08:00
userStore.setAccessToken("");
userStore.setRefreshToken("");
2025-04-14 14:43:29 +08:00
userStore.setExp(0)
2024-08-22 11:27:06 +08:00
router.replace(LOGIN_URL);
return Promise.reject(error);
}
};