// 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 (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"); console.log(modules); 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("/", ""); 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`], }); } }); router.addRoute(addNewRouter); router.addRoute({ path: '/:catchAll(.*)', name: 'NotFound', component: () => import("../pages/404.vue"), }) next({ ...to, replace: true }); } } else { //console.log("无登录信息,跳转到登录页"); next(`/login`); } } }; return { beforeEach, }; }