index.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import {
  2. createRouter,
  3. createWebHistory,
  4. type RouteRecordRaw,
  5. } from "vue-router";
  6. import Home from "@/views/index.vue";
  7. import Management from "@/views/management.vue";
  8. import Command from "@/views/command.vue";
  9. import ChatBI from "@/views/chatbi.vue";
  10. import Login from "@/views/login.vue";
  11. import { getAccessToken } from "@utils/auth";
  12. import { socialLogin } from "@/api/user";
  13. import * as authUtil from "@/utils/auth";
  14. const routes: RouteRecordRaw[] = [
  15. {
  16. path: "/",
  17. name: "Home",
  18. component: Home,
  19. },
  20. {
  21. path: "/login",
  22. name: "Login",
  23. component: Login,
  24. },
  25. {
  26. path: "/management",
  27. name: "Management",
  28. component: Management,
  29. },
  30. {
  31. path: "/command",
  32. name: "Command",
  33. component: Command,
  34. },
  35. {
  36. path: "/chatbi",
  37. name: "ChatBI",
  38. component: ChatBI,
  39. },
  40. ];
  41. const router = createRouter({
  42. history: createWebHistory(import.meta.env.BASE_URL),
  43. routes,
  44. scrollBehavior(to, from, savePosition) {
  45. // 始终滚动到顶部
  46. return { left: 0, top: 0 };
  47. },
  48. });
  49. export const resetRouter = (): void => {
  50. const resetWhiteNameList = ["Redirect", "Login", "NoFind", "Root"];
  51. router.getRoutes().forEach((route) => {
  52. const { name } = route;
  53. if (name && !resetWhiteNameList.includes(name as string)) {
  54. router.hasRoute(name) && router.removeRoute(name);
  55. }
  56. });
  57. };
  58. const whiteList = ["/login", "/social-login", "/auth-redirect"];
  59. router.beforeEach(async (to, from, next) => {
  60. if (getAccessToken()) {
  61. if (to.path === "/login") {
  62. next({ path: "/" });
  63. } else {
  64. next();
  65. }
  66. } else {
  67. if (whiteList.indexOf(to.path) !== -1) {
  68. // const code = to.query.code;
  69. // if (code) {
  70. // const res = await socialLogin(
  71. // "20",
  72. // typeof code === "string" ? code : "",
  73. // "22"
  74. // );
  75. // console.log(">>>>>>>>>>>>>>>>>>>>>>>>>", res);
  76. // authUtil.setToken(res);
  77. // next({ path: "/" });
  78. // } else {
  79. // next(); // 正常导航
  80. // }
  81. next();
  82. } else {
  83. next(`/login`);
  84. }
  85. }
  86. });
  87. export default router;