index.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 } = useStore();
  51. const token = true;
  52. const skipPath = ['/login', '/register', '/test', '/testEcharts']
  53. if (skipPath.includes(_to.path)) {
  54. next();
  55. } else {
  56. if (token && routerList && routerList.length > 0) {
  57. if (asyncRoutesMark) {
  58. console.log(routers, '<=== 以及有了')
  59. next();
  60. } else {
  61. setAsyncRoutesMark(true)
  62. const newRouters: any = routers
  63. const addNewRouter = newRouters.find((item: any) => item.name == 'home')
  64. routerList.forEach((item: any) => {
  65. addNewRouter?.children.push({
  66. path: item.path,
  67. name: item.name,
  68. meta: {},
  69. component: () => import(`@/pages/${item.name}/index.vue`),
  70. })
  71. })
  72. router.addRoute(addNewRouter);
  73. next({ ..._to, replace: true });
  74. }
  75. } else {
  76. console.log("无登录信息,跳转到登录页");
  77. next(`/login`);
  78. }
  79. }
  80. console.log(routerList);
  81. });
  82. export default router;