routerGuards.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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"];
  12. if (skipPath.includes(to.path)) {
  13. next();
  14. } else if(to.path === '/biReport') {
  15. next(`/biReport/cusReportForm`);
  16. } else {
  17. if (token && routerList && routerList.length > 0) {
  18. if (asyncRoutesMark) {
  19. next();
  20. } else {
  21. setAsyncRoutesMark(true);
  22. const newRouters: any = routers;
  23. const addNewRouter = newRouters.find(
  24. (item: any) => item.path == "/home"
  25. );
  26. let modules = import.meta.glob("@/pages/**/*.vue");
  27. routerList.forEach((item: any, index: number) => {
  28. let filePath = item.path.replace("/", "")
  29. const children = item.children;
  30. if (children && children.length > 0) {
  31. children.forEach((child: any) => {
  32. let childFilePath = child.path.replace("/", "");
  33. addNewRouter?.children.push({
  34. path: child.path,
  35. name: child.name,
  36. meta: {},
  37. component: modules[`/src/pages/${childFilePath}/index.vue`]
  38. });
  39. });
  40. } else {
  41. addNewRouter?.children.push({
  42. path: item.path,
  43. name: item.name,
  44. meta: {},
  45. component: modules[`/src/pages/${filePath}/index.vue`],
  46. });
  47. if(item.childrenList && item.childrenList.length > 0) {
  48. addNewRouter.children[index + 1].children = item.childrenList.map((child: any) => {
  49. let childFilePath = child.path.replace("/", "");
  50. return {
  51. path: child.path,
  52. name: child.name,
  53. meta: { parentPath: item.path },
  54. component: modules[`/src/pages/${childFilePath}/index.vue`]
  55. }
  56. })
  57. }
  58. }
  59. });
  60. router.addRoute(addNewRouter);
  61. router.addRoute({
  62. path: '/:catchAll(.*)',
  63. name: 'NotFound',
  64. component: () => import("../pages/404.vue"),
  65. })
  66. console.log(router.getRoutes(), '<==== router.getRoutes()')
  67. next({ ...to, replace: true });
  68. }
  69. } else {
  70. //console.log("无登录信息,跳转到登录页");
  71. next(`/login`);
  72. }
  73. }
  74. };
  75. return {
  76. beforeEach,
  77. };
  78. }