index.ts 9.0 KB

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