utils.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import {
  2. RouterHistory,
  3. RouteRecordRaw,
  4. RouteComponent,
  5. createWebHistory,
  6. createWebHashHistory,
  7. RouteRecordNormalized
  8. } from "vue-router";
  9. import { router } from "./index";
  10. import { loadEnv } from "../../build";
  11. import { cloneDeep } from "lodash-unified";
  12. import { useTimeoutFn } from "@vueuse/core";
  13. import { RouteConfigs } from "/@/layout/types";
  14. import { buildHierarchyTree } from "@pureadmin/utils";
  15. import { usePermissionStoreHook } from "/@/store/modules/permission";
  16. const IFrame = () => import("/@/layout/frameView.vue");
  17. // https://cn.vitejs.dev/guide/features.html#glob-import
  18. const modulesRoutes = import.meta.glob("/src/views/**/*.{vue,tsx}");
  19. // 动态路由
  20. import { getAsyncRoutes } from "/@/api/routes";
  21. // 按照路由中meta下的rank等级升序来排序路由
  22. function ascending(arr: any[]) {
  23. arr.forEach(v => {
  24. if (v?.meta?.rank === null) v.meta.rank = undefined;
  25. if (v?.meta?.rank === 0) {
  26. if (v.name !== "Home" && v.path !== "/") {
  27. console.warn("rank only the home page can be 0");
  28. }
  29. }
  30. });
  31. return arr.sort(
  32. (a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
  33. return a?.meta?.rank - b?.meta?.rank;
  34. }
  35. );
  36. }
  37. // 过滤meta中showLink为false的路由
  38. function filterTree(data: RouteComponent[]) {
  39. const newTree = cloneDeep(data).filter(
  40. (v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
  41. );
  42. newTree.forEach(
  43. (v: { children }) => v.children && (v.children = filterTree(v.children))
  44. );
  45. return newTree;
  46. }
  47. // 批量删除缓存路由(keepalive)
  48. function delAliveRoutes(delAliveRouteList: Array<RouteConfigs>) {
  49. delAliveRouteList.forEach(route => {
  50. usePermissionStoreHook().cacheOperate({
  51. mode: "delete",
  52. name: route?.name
  53. });
  54. });
  55. }
  56. // 通过path获取父级路径
  57. function getParentPaths(path: string, routes: RouteRecordRaw[]) {
  58. // 深度遍历查找
  59. function dfs(routes: RouteRecordRaw[], path: string, parents: string[]) {
  60. for (let i = 0; i < routes.length; i++) {
  61. const item = routes[i];
  62. // 找到path则返回父级path
  63. if (item.path === path) return parents;
  64. // children不存在或为空则不递归
  65. if (!item.children || !item.children.length) continue;
  66. // 往下查找时将当前path入栈
  67. parents.push(item.path);
  68. if (dfs(item.children, path, parents).length) return parents;
  69. // 深度遍历查找未找到时当前path 出栈
  70. parents.pop();
  71. }
  72. // 未找到时返回空数组
  73. return [];
  74. }
  75. return dfs(routes, path, []);
  76. }
  77. // 查找对应path的路由信息
  78. function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
  79. let res = routes.find((item: { path: string }) => item.path == path);
  80. if (res) {
  81. return res;
  82. } else {
  83. for (let i = 0; i < routes.length; i++) {
  84. if (
  85. routes[i].children instanceof Array &&
  86. routes[i].children.length > 0
  87. ) {
  88. res = findRouteByPath(path, routes[i].children);
  89. if (res) {
  90. return res;
  91. }
  92. }
  93. }
  94. return null;
  95. }
  96. }
  97. function addPathMatch() {
  98. if (!router.hasRoute("pathMatch")) {
  99. router.addRoute({
  100. path: "/:pathMatch(.*)",
  101. name: "pathMatch",
  102. redirect: "/error/404"
  103. });
  104. }
  105. }
  106. // 初始化路由
  107. function initRouter(name: string) {
  108. return new Promise(resolve => {
  109. getAsyncRoutes({ name }).then(({ info }) => {
  110. if (info.length === 0) {
  111. usePermissionStoreHook().changeSetting(info);
  112. } else {
  113. formatFlatteningRoutes(addAsyncRoutes(info)).map(
  114. (v: RouteRecordRaw) => {
  115. // 防止重复添加路由
  116. if (
  117. router.options.routes[0].children.findIndex(
  118. value => value.path === v.path
  119. ) !== -1
  120. ) {
  121. return;
  122. } else {
  123. // 切记将路由push到routes后还需要使用addRoute,这样路由才能正常跳转
  124. router.options.routes[0].children.push(v);
  125. // 最终路由进行升序
  126. ascending(router.options.routes[0].children);
  127. if (!router.hasRoute(v?.name)) router.addRoute(v);
  128. const flattenRouters: any = router
  129. .getRoutes()
  130. .find(n => n.path === "/");
  131. router.addRoute(flattenRouters);
  132. }
  133. resolve(router);
  134. }
  135. );
  136. usePermissionStoreHook().changeSetting(info);
  137. }
  138. addPathMatch();
  139. });
  140. });
  141. }
  142. /**
  143. * 将多级嵌套路由处理成一维数组
  144. * @param routesList 传入路由
  145. * @returns 返回处理后的一维路由
  146. */
  147. function formatFlatteningRoutes(routesList: RouteRecordRaw[]) {
  148. if (routesList.length === 0) return routesList;
  149. let hierarchyList = buildHierarchyTree(routesList);
  150. for (let i = 0; i < hierarchyList.length; i++) {
  151. if (hierarchyList[i].children) {
  152. hierarchyList = hierarchyList
  153. .slice(0, i + 1)
  154. .concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
  155. }
  156. }
  157. return hierarchyList;
  158. }
  159. /**
  160. * 一维数组处理成多级嵌套数组(三级及以上的路由全部拍成二级,keep-alive 只支持到二级缓存)
  161. * https://github.com/xiaoxian521/vue-pure-admin/issues/67
  162. * @param routesList 处理后的一维路由菜单数组
  163. * @returns 返回将一维数组重新处理成规定路由的格式
  164. */
  165. function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
  166. if (routesList.length === 0) return routesList;
  167. const newRoutesList: RouteRecordRaw[] = [];
  168. routesList.forEach((v: RouteRecordRaw) => {
  169. if (v.path === "/") {
  170. newRoutesList.push({
  171. component: v.component,
  172. name: v.name,
  173. path: v.path,
  174. redirect: v.redirect,
  175. meta: v.meta,
  176. children: []
  177. });
  178. } else {
  179. newRoutesList[0].children.push({ ...v });
  180. }
  181. });
  182. return newRoutesList;
  183. }
  184. // 处理缓存路由(添加、删除、刷新)
  185. function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) {
  186. switch (mode) {
  187. case "add":
  188. matched.forEach(v => {
  189. usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
  190. });
  191. break;
  192. case "delete":
  193. usePermissionStoreHook().cacheOperate({
  194. mode: "delete",
  195. name: matched[matched.length - 1].name
  196. });
  197. break;
  198. default:
  199. usePermissionStoreHook().cacheOperate({
  200. mode: "delete",
  201. name: matched[matched.length - 1].name
  202. });
  203. useTimeoutFn(() => {
  204. matched.forEach(v => {
  205. usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
  206. });
  207. }, 100);
  208. }
  209. }
  210. // 过滤后端传来的动态路由 重新生成规范路由
  211. function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
  212. if (!arrRoutes || !arrRoutes.length) return;
  213. const modulesRoutesKeys = Object.keys(modulesRoutes);
  214. arrRoutes.forEach((v: RouteRecordRaw) => {
  215. // 将backstage属性加入meta,标识此路由为后端返回路由
  216. v.meta.backstage = true;
  217. // 父级的redirect属性取值:如果子级存在且父级的redirect属性不存在,默认取第一个子级的path;如果子级存在且父级的redirect属性存在,取存在的redirect属性,会覆盖默认值
  218. if (v?.children && !v.redirect) v.redirect = v.children[0].path;
  219. // 父级的name属性取值:如果子级存在且父级的name属性不存在,默认取第一个子级的name;如果子级存在且父级的name属性存在,取存在的name属性,会覆盖默认值
  220. if (v?.children && !v.name) v.name = v.children[0].name;
  221. if (v.meta?.frameSrc) v.component = IFrame;
  222. // 对后端传component组件路径和不传做兼容(如果后端传component组件路径,那么path可以随便写,如果不传,component组件路径会跟path保持一致)
  223. const index = v?.component
  224. ? modulesRoutesKeys.findIndex(ev => ev.includes(v.component as any))
  225. : modulesRoutesKeys.findIndex(ev => ev.includes(v.path));
  226. v.component = modulesRoutes[modulesRoutesKeys[index]];
  227. if (v.children) {
  228. addAsyncRoutes(v.children);
  229. }
  230. });
  231. return arrRoutes;
  232. }
  233. // 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html
  234. function getHistoryMode(): RouterHistory {
  235. const routerHistory = loadEnv().VITE_ROUTER_HISTORY;
  236. // len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
  237. const historyMode = routerHistory.split(",");
  238. const leftMode = historyMode[0];
  239. const rightMode = historyMode[1];
  240. // no param
  241. if (historyMode.length === 1) {
  242. if (leftMode === "hash") {
  243. return createWebHashHistory("");
  244. } else if (leftMode === "h5") {
  245. return createWebHistory("");
  246. }
  247. } //has param
  248. else if (historyMode.length === 2) {
  249. if (leftMode === "hash") {
  250. return createWebHashHistory(rightMode);
  251. } else if (leftMode === "h5") {
  252. return createWebHistory(rightMode);
  253. }
  254. }
  255. }
  256. // 是否有权限
  257. function hasPermissions(value: Array<string>): boolean {
  258. if (value && value instanceof Array && value.length > 0) {
  259. const roles = usePermissionStoreHook().buttonAuth;
  260. const permissionRoles = value;
  261. const hasPermission = roles.some(role => {
  262. return permissionRoles.includes(role);
  263. });
  264. if (!hasPermission) {
  265. return false;
  266. }
  267. return true;
  268. } else {
  269. return false;
  270. }
  271. }
  272. export {
  273. ascending,
  274. filterTree,
  275. initRouter,
  276. hasPermissions,
  277. getHistoryMode,
  278. addAsyncRoutes,
  279. delAliveRoutes,
  280. getParentPaths,
  281. findRouteByPath,
  282. handleAliveRoute,
  283. formatTwoStageRoutes,
  284. formatFlatteningRoutes
  285. };