index.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. import { createRouter, createWebHashHistory } from 'vue-router';
  2. import NProgress from 'nprogress';
  3. import 'nprogress/nprogress.css';
  4. import pinia from '/@/stores/index';
  5. import { storeToRefs } from 'pinia';
  6. import { useKeepALiveNames } from '/@/stores/keepAliveNames';
  7. import { useRoutesList } from '/@/stores/routesList';
  8. import { useThemeConfig } from '/@/stores/themeConfig';
  9. import { Session } from '/@/utils/storage';
  10. import { staticRoutes, notFoundAndNoPower } from '/@/router/route';
  11. import { initFrontEndControlRoutes } from '/@/router/frontEnd';
  12. import { initBackEndControlRoutes } from '/@/router/backEnd';
  13. /**
  14. * 1、前端控制路由时:isRequestRoutes 为 false,需要写 roles,需要走 setFilterRoute 方法。
  15. * 2、后端控制路由时:isRequestRoutes 为 true,不需要写 roles,不需要走 setFilterRoute 方法),
  16. * 相关方法已拆解到对应的 `backEnd.ts` 与 `frontEnd.ts`(他们互不影响,不需要同时改 2 个文件)。
  17. * 特别说明:
  18. * 1、前端控制:路由菜单由前端去写(无菜单管理界面,有角色管理界面),角色管理中有 roles 属性,需返回到 userInfo 中。
  19. * 2、后端控制:路由菜单由后端返回(有菜单管理界面、有角色管理界面)
  20. */
  21. // 读取 `/src/stores/themeConfig.ts` 是否开启后端控制路由配置
  22. const storesThemeConfig = useThemeConfig(pinia);
  23. const { themeConfig } = storeToRefs(storesThemeConfig);
  24. const { isRequestRoutes } = themeConfig.value;
  25. /**
  26. * 创建一个可以被 Vue 应用程序使用的路由实例
  27. * @method createRouter(options: RouterOptions): Router
  28. * @link 参考:https://next.router.vuejs.org/zh/api/#createrouter
  29. */
  30. export const router = createRouter({
  31. history: createWebHashHistory(),
  32. /**
  33. * 说明:
  34. * 1、notFoundAndNoPower 默认添加 404、401 界面,防止一直提示 No match found for location with path 'xxx'
  35. * 2、backEnd.ts(后端控制路由)、frontEnd.ts(前端控制路由) 中也需要加 notFoundAndNoPower 404、401 界面。
  36. * 防止 404、401 不在 layout 布局中,不设置的话,404、401 界面将全屏显示
  37. */
  38. routes: [...notFoundAndNoPower, ...staticRoutes],
  39. });
  40. /**
  41. * 路由多级嵌套数组处理成一维数组
  42. * @param arr 传入路由菜单数据数组
  43. * @returns 返回处理后的一维路由菜单数组
  44. */
  45. export function formatFlatteningRoutes(arr: any) {
  46. if (arr.length <= 0) return false;
  47. for (let i = 0; i < arr.length; i++) {
  48. if (arr[i].children) {
  49. arr = arr.slice(0, i + 1).concat(arr[i].children, arr.slice(i + 1));
  50. }
  51. }
  52. return arr;
  53. }
  54. /**
  55. * 一维数组处理成多级嵌套数组(只保留二级:也就是二级以上全部处理成只有二级,keep-alive 支持二级缓存)
  56. * @description isKeepAlive 处理 `name` 值,进行缓存。顶级关闭,全部不缓存
  57. * @link 参考:https://v3.cn.vuejs.org/api/built-in-components.html#keep-alive
  58. * @param arr 处理后的一维路由菜单数组
  59. * @returns 返回将一维数组重新处理成 `定义动态路由(dynamicRoutes)` 的格式
  60. */
  61. export function formatTwoStageRoutes(arr: any) {
  62. if (arr.length <= 0) return false;
  63. const newArr: any = [];
  64. const cacheList: Array<string> = [];
  65. arr.forEach((v: any) => {
  66. if (v.path == null || v.path == undefined) return;
  67. if (v.path === '/') {
  68. newArr.push({ component: v.component, name: v.name, path: v.path, redirect: v.redirect, meta: v.meta, children: [] });
  69. } else {
  70. // 判断是否是动态路由(xx/:id/:name),用于 tagsView 等中使用
  71. // 修复:https://gitee.com/lyt-top/vue-next-admin/issues/I3YX6G
  72. if (v.path.indexOf('/:') > -1) {
  73. v.meta['isDynamic'] = true;
  74. v.meta['isDynamicPath'] = v.path;
  75. }
  76. newArr[0].children.push({ ...v });
  77. // 存 name 值,keep-alive 中 include 使用,实现路由的缓存
  78. // 路径:/@/layout/routerView/parent.vue
  79. if (newArr[0].meta.isKeepAlive && v.meta.isKeepAlive) {
  80. cacheList.push(v.name);
  81. const stores = useKeepALiveNames(pinia);
  82. stores.setCacheKeepAlive(cacheList);
  83. }
  84. }
  85. });
  86. return newArr;
  87. }
  88. // 路由加载前
  89. router.beforeEach(async (to, from, next) => {
  90. NProgress.configure({ showSpinner: false });
  91. if (to.meta.title) NProgress.start();
  92. const token = Session.get('token');
  93. if (to.path === '/login' && !token) {
  94. next();
  95. NProgress.done();
  96. } else {
  97. if (!token) {
  98. next(`/login?redirect=${to.path}&params=${JSON.stringify(to.query ? to.query : to.params)}`);
  99. Session.clear();
  100. NProgress.done();
  101. } else if (token && to.path === '/login') {
  102. next('/dashboard/home');
  103. NProgress.done();
  104. } else {
  105. const storesRoutesList = useRoutesList(pinia);
  106. const { routesList } = storeToRefs(storesRoutesList);
  107. if (routesList.value.length === 0) {
  108. if (isRequestRoutes) {
  109. // 后端控制路由:路由数据初始化,防止刷新时丢失
  110. await initBackEndControlRoutes();
  111. // 解决刷新时,一直跳 404 页面问题,关联问题 No match found for location with path 'xxx'
  112. // to.query 防止页面刷新时,普通路由带参数时,参数丢失。动态路由(xxx/:id/:name")isDynamic 无需处理
  113. next({ path: to.path, query: to.query });
  114. } else {
  115. // https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
  116. await initFrontEndControlRoutes();
  117. next({ path: to.path, query: to.query });
  118. }
  119. } else {
  120. next();
  121. }
  122. }
  123. }
  124. });
  125. // 路由加载后
  126. router.afterEach(() => {
  127. NProgress.done();
  128. });
  129. // 导出路由
  130. export default router;