index.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import { createRouter, createWebHashHistory, createWebHistory, RouteLocationNormalizedLoaded } from 'vue-router';
  2. import NProgress from 'nprogress';
  3. import 'nprogress/nprogress.css';
  4. import { store } from '/@/store/index';
  5. import { Session } from '/@/utils/storage';
  6. import { NextLoading } from '/@/utils/loading';
  7. import { staticRoutes, dynamicRoutes } from '/@/router/route';
  8. import { initFrontEndControlRoutes } from '/@/router/frontEnd';
  9. import { initBackEndControlRoutes } from '/@/router/backEnd';
  10. import { getTenantInfo, getToken } from "/@/utils/auth";
  11. const whiteList = ['/login', '/ssoBack', '/:tenant/login']
  12. function whiteListAllow(route: RouteLocationNormalizedLoaded) {
  13. const matchedPath = route.matched?.[0]?.path
  14. return whiteList.includes(route.path) || whiteList.includes(matchedPath)
  15. }
  16. /**
  17. * 创建一个可以被 Vue 应用程序使用的路由实例
  18. * @method createRouter(options: RouterOptions): Router
  19. * @link 参考:https://next.router.vuejs.org/zh/api/#createrouter
  20. */
  21. const router = createRouter({
  22. // 如果使用 golocal 打包,则路由使用 hash 模式
  23. history: import.meta.env.VITE_ROUTER_MODE === 'hash' ? createWebHashHistory() : createWebHistory(),
  24. routes: staticRoutes,
  25. });
  26. /**
  27. * 定义404界面
  28. * @link 参考:https://next.router.vuejs.org/zh/guide/essentials/history-mode.html#netlify
  29. */
  30. const pathMatch = {
  31. path: '/:path(.*)*',
  32. redirect: '/404',
  33. };
  34. /**
  35. * 路由多级嵌套数组处理成一维数组
  36. * @param arr 传入路由菜单数据数组
  37. * @returns 返回处理后的一维路由菜单数组
  38. */
  39. export function formatFlatteningRoutes(arr: any) {
  40. if (arr.length <= 0) return false;
  41. for (let i = 0; i < arr.length; i++) {
  42. if (arr[i].children) {
  43. arr = arr.slice(0, i + 1).concat(arr[i].children, arr.slice(i + 1));
  44. }
  45. }
  46. return arr;
  47. }
  48. /**
  49. * 一维数组处理成多级嵌套数组(只保留二级:也就是二级以上全部处理成只有二级,keep-alive 支持二级缓存)
  50. * @description isKeepAlive 处理 `name` 值,进行缓存。顶级关闭,全部不缓存
  51. * @link 参考:https://v3.cn.vuejs.org/api/built-in-components.html#keep-alive
  52. * @param arr 处理后的一维路由菜单数组
  53. * @returns 返回将一维数组重新处理成 `定义动态路由(dynamicRoutes)` 的格式
  54. */
  55. export function formatTwoStageRoutes(arr: any) {
  56. if (arr.length <= 0) return false;
  57. const newArr: any = [];
  58. const cacheList: Array<string> = [];
  59. arr.forEach((v: any) => {
  60. if (v.path === '/') {
  61. newArr.push({ component: v.component, name: v.name, path: v.path, redirect: v.redirect, meta: v.meta, children: [] });
  62. } else {
  63. // 判断是否是动态路由(xx/:id/:name),用于 tagsView 等中使用
  64. // 修复:https://gitee.com/lyt-top/vue-next-admin/issues/I3YX6G
  65. if (v.path.indexOf('/:') > -1) {
  66. v.meta['isDynamic'] = true;
  67. v.meta['isDynamicPath'] = v.path;
  68. }
  69. newArr[0].children.push({ ...v });
  70. // 存 name 值,keep-alive 中 include 使用,实现路由的缓存
  71. // 路径:/@/layout/routerView/parent.vue
  72. if (newArr[0].meta?.isKeepAlive && v.meta?.isKeepAlive) {
  73. cacheList.push(v.name);
  74. store.dispatch('keepAliveNames/setCacheKeepAlive', cacheList);
  75. }
  76. }
  77. });
  78. return newArr;
  79. }
  80. /**
  81. * 缓存多级嵌套数组处理后的一维数组
  82. * @description 用于 tagsView、菜单搜索中:未过滤隐藏的(isHide)
  83. */
  84. export function setCacheTagsViewRoutes() {
  85. // 获取有权限的路由,否则 tagsView、菜单搜索中无权限的路由也将显示
  86. let rolesRoutes = dynamicRoutes
  87. // 添加到 vuex setTagsViewRoutes 中
  88. store.dispatch('tagsViewRoutes/setTagsViewRoutes', formatTwoStageRoutes(formatFlatteningRoutes(rolesRoutes))[0].children);
  89. }
  90. /**
  91. * 判断路由 `meta.roles` 中是否包含当前登录用户权限字段
  92. * @param roles 用户权限标识,在 userInfos(用户信息)的 roles(登录页登录时缓存到浏览器)数组
  93. * @param route 当前循环时的路由项
  94. * @returns 返回对比后有权限的路由项
  95. */
  96. export function hasRoles(roles: any, route: any) {
  97. if (route.meta && route.meta.roles) return roles.some((role: any) => route.meta.roles.includes(role));
  98. else return true;
  99. }
  100. /**
  101. * 获取当前用户权限标识去比对路由表,设置递归过滤有权限的路由
  102. * @param routes 当前路由 children
  103. * @param roles 用户权限标识,在 userInfos(用户信息)的 roles(登录页登录时缓存到浏览器)数组
  104. * @returns 返回有权限的路由数组 `meta.roles` 中控制
  105. */
  106. export function setFilterHasRolesMenu(routes: any, roles: any) {
  107. const menu: any = [];
  108. routes.forEach((route: any) => {
  109. const item = { ...route };
  110. if (hasRoles(roles, item)) {
  111. menu.push(item);
  112. }
  113. });
  114. return menu;
  115. }
  116. /**
  117. * 设置递归过滤有权限的路由到 vuex routesList 中(已处理成多级嵌套路由)及缓存多级嵌套数组处理后的一维数组
  118. * @description 用于左侧菜单、横向菜单的显示
  119. * @description 用于 tagsView、菜单搜索中:未过滤隐藏的(isHide)
  120. */
  121. export function setFilterMenuAndCacheTagsViewRoutes() {
  122. store.dispatch('routesList/setRoutesList', dynamicRoutes[0].children);
  123. setCacheTagsViewRoutes();
  124. }
  125. /**
  126. * 获取当前用户权限标识去比对路由表(未处理成多级嵌套路由)
  127. * @description 这里主要用于动态路由的添加,router.addRoute
  128. * @link 参考:https://next.router.vuejs.org/zh/api/#addroute
  129. * @param chil dynamicRoutes(/@/router/route)第一个顶级 children 的下路由集合
  130. * @returns 返回有当前用户权限标识的路由数组
  131. */
  132. export function setFilterRoute(chil: any) {
  133. let filterRoute: any = [];
  134. chil.forEach((route: any) => {
  135. if (route.meta.roles) {
  136. route.meta.roles.forEach((metaRoles: any) => {
  137. store.state.userInfos.userInfos.roles.forEach((roles: any) => {
  138. if (metaRoles === roles) filterRoute.push({ ...route });
  139. });
  140. });
  141. }
  142. });
  143. return filterRoute;
  144. }
  145. /**
  146. * 获取有当前用户权限标识的路由数组,进行对原路由的替换
  147. * @description 替换 dynamicRoutes(/@/router/route)第一个顶级 children 的路由
  148. * @returns 返回替换后的路由数组
  149. */
  150. export function setFilterRouteEnd() {
  151. let filterRouteEnd: any = formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes));
  152. filterRouteEnd[0].children = [...filterRouteEnd[0].children, { ...pathMatch }];
  153. return filterRouteEnd;
  154. }
  155. /**
  156. * 添加动态路由
  157. * @method router.addRoute
  158. * @description 此处循环为 dynamicRoutes(/@/router/route)第一个顶级 children 的路由一维数组,非多级嵌套
  159. * @link 参考:https://next.router.vuejs.org/zh/api/#addroute
  160. */
  161. export async function setAddRoute() {
  162. await setFilterRouteEnd().forEach((route: RouteRecordRaw) => {
  163. const routeName: any = route.name;
  164. if (!router.hasRoute(routeName)) router.addRoute(route);
  165. });
  166. // 修改首页重定向的地址,从后台配置中获取首页的地址并在登录之后和刷新页面时进行修改
  167. const sysinfo = JSON.parse(localStorage.sysinfo || '{}');
  168. const homePage = router.getRoutes().find((item) => item.path === '/');
  169. homePage && sysinfo.systemHomePageRoute && (homePage.redirect = sysinfo.systemHomePageRoute) || '/home';
  170. }
  171. /**
  172. * 删除/重置路由
  173. * @method router.removeRoute
  174. * @description 此处循环为 dynamicRoutes(/@/router/route)第一个顶级 children 的路由一维数组,非多级嵌套
  175. * @link 参考:https://next.router.vuejs.org/zh/api/#push
  176. */
  177. export async function resetRoute() {
  178. await setFilterRouteEnd().forEach((route: RouteRecordRaw) => {
  179. const routeName: any = route.name;
  180. router.hasRoute(routeName) && router.removeRoute(routeName);
  181. });
  182. }
  183. // isRequestRoutes 为 true,则开启后端控制路由,路径:`/src/store/modules/themeConfig.ts`
  184. const { isRequestRoutes } = store.state.themeConfig.themeConfig;
  185. // 前端控制路由:初始化方法,防止刷新时路由丢失
  186. if (!isRequestRoutes) initFrontEndControlRoutes();
  187. // 路由加载前
  188. router.beforeEach(async (to, from, next) => {
  189. NProgress.configure({ showSpinner: false });
  190. if (to.meta?.title) NProgress.start();
  191. // 系统初始化
  192. if (to.path === '/dbInit') {
  193. next();
  194. NProgress.done();
  195. }
  196. // 正常流程
  197. const token = getToken();
  198. if (whiteListAllow(to) && !token) {
  199. next();
  200. NProgress.done();
  201. } else {
  202. if (!token) {
  203. const params = Object.keys(to.query).length || Object.keys(to.params).length
  204. let paramsStr = ''
  205. if (params) {
  206. paramsStr = `&params=${JSON.stringify(Object.keys(to.query).length ? to.query : to.params)}`
  207. }
  208. // 如果当前是租户并且是企业版,则跳转到租户登录页
  209. const tenantCode = getTenantInfo()?.code
  210. next(`${tenantCode && sessionStorage.isEnterprise ? '/' + tenantCode : ''}/login?redirect=${to.path}${paramsStr}`);
  211. Session.clear();
  212. resetRoute();
  213. NProgress.done();
  214. } else if (token && whiteListAllow(to)) {
  215. next('/');
  216. NProgress.done();
  217. } else {
  218. if (to.matched?.[0]?.path === '/designer/:id') {
  219. next();
  220. NProgress.done();
  221. return
  222. }
  223. if (store.state.routesList.routesList.length === 0) {
  224. if (isRequestRoutes) {
  225. // 后端控制路由:路由数据初始化,防止刷新时丢失
  226. await initBackEndControlRoutes();
  227. // 动态添加路由:防止非首页刷新时跳转回首页的问题
  228. // 确保 addRoute() 时动态添加的路由已经被完全加载上去
  229. next({ ...to, replace: true });
  230. }
  231. } else {
  232. next();
  233. }
  234. }
  235. }
  236. });
  237. // 路由加载后
  238. router.afterEach(() => {
  239. NProgress.done();
  240. NextLoading.done();
  241. });
  242. // 导出路由
  243. export default router;