index.ts 5.5 KB

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