routerGuards.ts 2.3 KB

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