// 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"]; if (skipPath.includes(to.path)) { next(); } else if(to.path === '/biReport') { next(`/biReport/cusReportForm`); } else { if (token && routerList && routerList.length > 0) { if (asyncRoutesMark) { next(); } else { setAsyncRoutesMark(true); const newRouters: any = routers; const addNewRouter = newRouters.find( (item: any) => item.path == "/home" ); let modules = import.meta.glob("@/pages/**/*.vue"); routerList.forEach((item: any, index: number) => { let filePath = item.path.replace("/", "") const children = item.children; if (children && children.length > 0) { children.forEach((child: any) => { let childFilePath = child.path.replace("/", ""); addNewRouter?.children.push({ path: child.path, name: child.name, meta: {}, component: modules[`/src/pages/${childFilePath}/index.vue`] }); }); } else { addNewRouter?.children.push({ path: item.path, name: item.name, meta: {}, component: modules[`/src/pages/${filePath}/index.vue`], }); if(item.childrenList && item.childrenList.length > 0) { addNewRouter.children[index + 1].children = 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(addNewRouter); 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, }; }