routerGuards.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. const beforeEach = (to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
  6. const routerList = useStore().routers;
  7. const routers = router.getRoutes();
  8. const { setAsyncRoutesMark, asyncRoutesMark, getToken } = useStore();
  9. const token = getToken;
  10. const skipPath = ["/login", "/register", "/test", "/testEcharts"];
  11. if (skipPath.includes(to.path)) {
  12. next();
  13. } else {
  14. if (token && routerList && routerList.length > 0) {
  15. if (asyncRoutesMark) {
  16. next();
  17. } else {
  18. setAsyncRoutesMark(true);
  19. const newRouters: any = routers;
  20. const addNewRouter = newRouters.find(
  21. (item: any) => item.path == "/home"
  22. );
  23. let modules = import.meta.glob("@/pages/**/*.vue");
  24. console.log(modules);
  25. routerList.forEach((item: any) => {
  26. let filePath = item.path.replace("/", "")
  27. if (item.children && item.children.length > 0) {
  28. item.children.forEach((child: any) => {
  29. let childFilePath = child.path.replace("/", "");
  30. addNewRouter?.children.push({
  31. path: child.path,
  32. name: child.name,
  33. meta: {},
  34. component: modules[`/src/pages/${childFilePath}/index.vue`]
  35. });
  36. });
  37. } else {
  38. addNewRouter?.children.push({
  39. path: item.path,
  40. name: item.name,
  41. meta: {},
  42. component: modules[`/src/pages/${filePath}/index.vue`],
  43. });
  44. }
  45. });
  46. router.addRoute(addNewRouter);
  47. router.addRoute({
  48. path: '/:catchAll(.*)',
  49. name: 'NotFound',
  50. component: () => import("../pages/404.vue"),
  51. })
  52. next({ ...to, replace: true });
  53. }
  54. } else {
  55. //console.log("无登录信息,跳转到登录页");
  56. next(`/login`);
  57. }
  58. }
  59. };
  60. return {
  61. beforeEach,
  62. };
  63. }