123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- // src/router/routerGuards.ts
- import { RouteLocationNormalized, NavigationGuardNext, Router } from "vue-router";
- import { useStore } from "@/store/index";
- export function createRouterGuards(router: Router) {
- console.log('开始执行添加路由')
- const beforeEach = (to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
- const routerList = useStore().routers;
- const routers = router.getRoutes();
- const { setAsyncRoutesMark, asyncRoutesMark, getToken } = useStore();
- const token = getToken;
- const skipPath = ["/login", "/register", "/test", "/testEcharts", "/test/aitest"];
- if (skipPath.includes(to.path)) {
- next();
- } else {
- if (token && routerList && routerList.length > 0) {
- if (asyncRoutesMark) {
- next();
- } else {
- setAsyncRoutesMark(true);
- const modules = import.meta.glob("@/pages/**/*.vue");
-
- // 遍历菜单,动态添加到 'home' 路由下
- routerList.forEach((item: any) => {
- let filePath = item.path.replace("/", "");
-
- if (item.children && item.children.length > 0) {
- item.children.forEach((child: any) => {
- let childFilePath = child.path.replace("/", "");
- router.addRoute('home', {
- path: child.path,
- name: child.name,
- meta: {},
- component: modules[`/src/pages/${childFilePath}/index.vue`],
- });
- });
- } else {
- let childRoutes: any[] = [];
- if (item.childrenList && item.childrenList.length > 0) {
- childRoutes = item.childrenList.map((child: any) => {
- let childFilePath = child.path.replace("/", "");
- return {
- path: child.path,
- name: child.name,
- meta: { parentPath: item.path },
- component: modules[`/src/pages/${childFilePath}/index.vue`],
- };
- });
- }
-
- router.addRoute('home', {
- path: item.path,
- name: item.name,
- meta: {},
- component: modules[`/src/pages/${filePath}/index.vue`],
- redirect: item.path === '/biReport' ? `/biReport/cusReportForm` : '',
- children: childRoutes
- });
- }
- });
-
- // 添加404兜底
- router.addRoute({
- path: '/:catchAll(.*)',
- name: 'NotFound',
- component: () => import("../pages/404.vue"),
- });
-
- console.log(router.getRoutes(), '<==== router.getRoutes()');
-
- // ✅ 路由添加完毕后,重新进入当前页面,确保路由匹配
- next({ ...to, replace: true });
- }
- } else {
- //console.log("无登录信息,跳转到登录页");
- next(`/login`);
- }
- }
- };
- return {
- beforeEach,
- };
- }
|