routerGuards.ts 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // src/router/routerGuards.ts
  2. import { RouteLocationNormalized, NavigationGuardNext, Router } from "vue-router";
  3. import { useStore } from "@/store/index";
  4. export function createRouterGuards(router: Router) {
  5. console.log('开始执行添加路由')
  6. const beforeEach = (to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
  7. const routerList = useStore().routers;
  8. const routers = router.getRoutes();
  9. const { setAsyncRoutesMark, asyncRoutesMark, getToken } = useStore();
  10. const token = getToken;
  11. const skipPath = ["/login", "/register", "/test", "/testEcharts", "/test/aitest"];
  12. if (skipPath.includes(to.path)) {
  13. next();
  14. } else {
  15. if (token && routerList && routerList.length > 0) {
  16. if (asyncRoutesMark) {
  17. next();
  18. } else {
  19. setAsyncRoutesMark(true);
  20. const modules = import.meta.glob("@/pages/**/*.vue");
  21. // 遍历菜单,动态添加到 'home' 路由下
  22. routerList.forEach((item: any) => {
  23. let filePath = item.path.replace("/", "");
  24. if (item.children && item.children.length > 0) {
  25. item.children.forEach((child: any) => {
  26. let childFilePath = child.path.replace("/", "");
  27. router.addRoute('home', {
  28. path: child.path,
  29. name: child.name,
  30. meta: {},
  31. component: modules[`/src/pages/${childFilePath}/index.vue`],
  32. });
  33. });
  34. } else {
  35. let childRoutes: any[] = [];
  36. if (item.childrenList && item.childrenList.length > 0) {
  37. childRoutes = item.childrenList.map((child: any) => {
  38. let childFilePath = child.path.replace("/", "");
  39. return {
  40. path: child.path,
  41. name: child.name,
  42. meta: { parentPath: item.path },
  43. component: modules[`/src/pages/${childFilePath}/index.vue`],
  44. };
  45. });
  46. }
  47. router.addRoute('home', {
  48. path: item.path,
  49. name: item.name,
  50. meta: {},
  51. component: modules[`/src/pages/${filePath}/index.vue`],
  52. redirect: item.path === '/biReport' ? `/biReport/cusReportForm` : '',
  53. children: childRoutes
  54. });
  55. }
  56. });
  57. // 添加404兜底
  58. router.addRoute({
  59. path: '/:catchAll(.*)',
  60. name: 'NotFound',
  61. component: () => import("../pages/404.vue"),
  62. });
  63. console.log(router.getRoutes(), '<==== router.getRoutes()');
  64. // ✅ 路由添加完毕后,重新进入当前页面,确保路由匹配
  65. next({ ...to, replace: true });
  66. }
  67. } else {
  68. //console.log("无登录信息,跳转到登录页");
  69. next(`/login`);
  70. }
  71. }
  72. };
  73. return {
  74. beforeEach,
  75. };
  76. }