index.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { RouteRecordRaw, createRouter, createWebHistory } from "vue-router";
  2. import { useStore } from "@/store/index";
  3. export const routes: RouteRecordRaw[] = [
  4. {
  5. path: "/",
  6. redirect: "/login",
  7. },
  8. {
  9. name: "login",
  10. path: "/login",
  11. component: () => import("../pages/login.vue"),
  12. },
  13. {
  14. name: "register",
  15. path: "/register",
  16. component: () => import("../pages/register.vue"),
  17. },
  18. {
  19. name: "home",
  20. path: "/home",
  21. component: () => import("../pages/home.vue"),
  22. children: [
  23. // {
  24. // name: 'thread',
  25. // path: '/thread',
  26. // component: () => import("../pages/thread/thread.vue")
  27. // },
  28. ],
  29. },
  30. {
  31. name: "test",
  32. path: "/test",
  33. component: () => import("../pages/test/index.vue"),
  34. },
  35. {
  36. name: "testEcharts",
  37. path: "/testEcharts",
  38. component: () => import("../pages/test/echarts.vue"),
  39. },
  40. ];
  41. const router = createRouter({
  42. scrollBehavior: () => ({ left: 0, top: 0 }),
  43. history: createWebHistory(),
  44. routes,
  45. });
  46. router.beforeEach((to, _from, next) => {
  47. const routerList = useStore().routers;
  48. const routers = router.getRoutes();
  49. //console.log(routerList, routers);
  50. const { setAsyncRoutesMark, asyncRoutesMark, getToken } = useStore();
  51. const token = getToken;
  52. const skipPath = ["/login", "/register", "/test", "/testEcharts"];
  53. //console.log(token, '<==== token')
  54. if (skipPath.includes(to.path)) {
  55. next();
  56. } else {
  57. if (token && routerList && routerList.length > 0) {
  58. if (asyncRoutesMark) {
  59. next();
  60. } else {
  61. setAsyncRoutesMark(true);
  62. const newRouters: any = routers;
  63. const addNewRouter = newRouters.find(
  64. (item: any) => item.path == "/home"
  65. );
  66. routerList.forEach((item: any) => {
  67. let filePath = item.path.split("/")[1];
  68. if (item.children && item.children.length > 0) {
  69. item.children.forEach((child: any) => {
  70. let childFilePath = child.path.split("/")[1];
  71. addNewRouter?.children.push({
  72. path: child.path,
  73. name: child.name,
  74. meta: {},
  75. component: () =>
  76. import(`@/pages/${filePath}/${childFilePath}/index.vue`),
  77. });
  78. });
  79. } else {
  80. addNewRouter?.children.push({
  81. path: item.path,
  82. name: item.name,
  83. meta: {},
  84. component: () => import(`@/pages/${filePath}/index.vue`),
  85. });
  86. }
  87. });
  88. router.addRoute(addNewRouter);
  89. next({ ...to, replace: true });
  90. }
  91. } else {
  92. //console.log("无登录信息,跳转到登录页");
  93. next(`/login`);
  94. }
  95. }
  96. //console.log(routerList);
  97. });
  98. export default router;