utils.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import {
  2. type RouterHistory,
  3. type RouteRecordRaw,
  4. type RouteComponent,
  5. createWebHistory,
  6. createWebHashHistory
  7. } from "vue-router";
  8. import { router } from "./index";
  9. import { isProxy, toRaw } from "vue";
  10. import { useTimeoutFn } from "@vueuse/core";
  11. import {
  12. isString,
  13. cloneDeep,
  14. isAllEmpty,
  15. intersection,
  16. storageLocal,
  17. isIncludeAllChildren
  18. } from "@pureadmin/utils";
  19. import { getConfig } from "@/config";
  20. import { buildHierarchyTree } from "@/utils/tree";
  21. import { userKey, type DataInfo } from "@/utils/auth";
  22. import { type menuType, routerArrays } from "@/layout/types";
  23. import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
  24. import { usePermissionStoreHook } from "@/store/modules/permission";
  25. const IFrame = () => import("@/layout/frame.vue");
  26. // https://cn.vitejs.dev/guide/features.html#glob-import
  27. const modulesRoutes = import.meta.glob("/src/views/**/*.{vue,tsx}");
  28. // 动态路由
  29. import { getAsyncRoutes } from "@/api/routes";
  30. function handRank(routeInfo: any) {
  31. const { name, path, parentId, meta } = routeInfo;
  32. return isAllEmpty(parentId)
  33. ? (meta?.rank == null) ||
  34. (meta?.rank === 0 && name !== "Home" && path !== "/")
  35. ? true
  36. : false
  37. : false;
  38. }
  39. /** 按照路由中meta下的rank等级升序来排序路由 */
  40. function ascending(arr: any[]) {
  41. arr.forEach((v, index) => {
  42. // 当rank不存在时,根据顺序自动创建,首页路由永远在第一位
  43. if (handRank(v)) v.meta.rank = index + 2;
  44. });
  45. return arr.sort(
  46. (a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
  47. return a?.meta.rank - b?.meta.rank;
  48. }
  49. );
  50. }
  51. /** 过滤meta中showLink为false的菜单 */
  52. function filterTree(data: RouteComponent[]) {
  53. const newTree = cloneDeep(data).filter(
  54. (v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
  55. );
  56. newTree.forEach(
  57. (v: { children }) => v.children && (v.children = filterTree(v.children))
  58. );
  59. return newTree;
  60. }
  61. /** 过滤没有 children 的目录,以及泄漏到一级的二级子路由 */
  62. function filterChildrenTree(data: RouteComponent[]) {
  63. const newTree = cloneDeep(data).filter((v: any) => {
  64. // 有非空 children → 保留(正常的父级菜单)
  65. if (v?.children?.length > 0) return true;
  66. // children 为空数组 → 移除
  67. if (Array.isArray(v?.children)) return false;
  68. // children 为 undefined:可能是合法的顶层叶子路由,也可能是泄漏的二级子路由
  69. // 如果它的 path 是另一个顶级路由的子路径,说明是泄漏的二级路由 → 移除
  70. const isChild = data.some(
  71. (parent: any) =>
  72. parent !== v &&
  73. parent.path &&
  74. v.path &&
  75. v.path.startsWith(parent.path + "/")
  76. );
  77. return !isChild;
  78. });
  79. newTree.forEach(
  80. (v: { children }) => v.children && (v.children = filterTree(v.children))
  81. );
  82. return newTree;
  83. }
  84. /** 判断两个数组彼此是否存在相同值 */
  85. function isOneOfArray(a: Array<string>, b: Array<string>) {
  86. return Array.isArray(a) && Array.isArray(b)
  87. ? intersection(a, b).length > 0
  88. ? true
  89. : false
  90. : true;
  91. }
  92. /** 从localStorage里取出当前登录用户的角色roles,过滤无权限的菜单 */
  93. function filterNoPermissionTree(data: RouteComponent[]) {
  94. const currentRoles =
  95. storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [];
  96. const newTree = cloneDeep(data).filter((v: any) =>
  97. isOneOfArray(v.meta?.roles, currentRoles)
  98. );
  99. newTree.forEach(
  100. (v: any) => v.children && (v.children = filterNoPermissionTree(v.children))
  101. );
  102. return filterChildrenTree(newTree);
  103. }
  104. /** 通过指定 `key` 获取父级路径集合,默认 `key` 为 `path` */
  105. function getParentPaths(value: string, routes: RouteRecordRaw[], key = "path") {
  106. // 深度遍历查找
  107. function dfs(routes: RouteRecordRaw[], value: string, parents: string[]) {
  108. for (let i = 0; i < routes.length; i++) {
  109. const item = routes[i];
  110. // 返回父级path
  111. if (item[key] === value) return parents;
  112. // children不存在或为空则不递归
  113. if (!item.children || !item.children.length) continue;
  114. // 往下查找时将当前path入栈
  115. parents.push(item.path);
  116. if (dfs(item.children, value, parents).length) return parents;
  117. // 深度遍历查找未找到时当前path 出栈
  118. parents.pop();
  119. }
  120. // 未找到时返回空数组
  121. return [];
  122. }
  123. return dfs(routes, value, []);
  124. }
  125. /** 查找对应 `path` 的路由信息 */
  126. function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
  127. let res = routes.find((item: { path: string }) => item.path == path);
  128. if (res) {
  129. return isProxy(res) ? toRaw(res) : res;
  130. } else {
  131. for (let i = 0; i < routes.length; i++) {
  132. if (
  133. routes[i].children instanceof Array &&
  134. routes[i].children.length > 0
  135. ) {
  136. res = findRouteByPath(path, routes[i].children);
  137. if (res) {
  138. return isProxy(res) ? toRaw(res) : res;
  139. }
  140. }
  141. }
  142. return null;
  143. }
  144. }
  145. /** 动态路由注册完成后,再添加全屏404(页面不存在)页面,避免刷新动态路由页面时误跳转到404页面 */
  146. function addPathMatch() {
  147. if (!router.hasRoute("pathMatch")) {
  148. router.addRoute({
  149. path: "/:pathMatch(.*)*",
  150. name: "PageNotFound",
  151. component: () => import("@/views/error/404.vue"),
  152. meta: {
  153. title: "menus.purePageNotFound",
  154. showLink: false
  155. }
  156. });
  157. }
  158. }
  159. /** 处理动态路由(后端返回的路由) */
  160. function handleAsyncRoutes(routeList) {
  161. if (routeList.length === 0) {
  162. usePermissionStoreHook().handleWholeMenus(routeList);
  163. } else {
  164. formatFlatteningRoutes(addAsyncRoutes(routeList)).map(
  165. (v: RouteRecordRaw) => {
  166. // 防止重复添加路由
  167. if (
  168. router.options.routes[0].children.findIndex(
  169. value => value.path === v.path
  170. ) !== -1
  171. ) {
  172. return;
  173. } else {
  174. // 切记将路由push到routes后还需要使用addRoute,这样路由才能正常跳转
  175. router.options.routes[0].children.push(v);
  176. // 最终路由进行升序
  177. ascending(router.options.routes[0].children);
  178. if (!router.hasRoute(v?.name)) router.addRoute(v);
  179. const flattenRouters: any = router
  180. .getRoutes()
  181. .find(n => n.path === "/");
  182. // 保持router.options.routes[0].children与path为"/"的children一致,防止数据不一致导致异常
  183. flattenRouters.children = router.options.routes[0].children;
  184. router.addRoute(flattenRouters);
  185. }
  186. }
  187. );
  188. usePermissionStoreHook().handleWholeMenus(routeList);
  189. }
  190. if (!useMultiTagsStoreHook().getMultiTagsCache) {
  191. useMultiTagsStoreHook().handleTags("equal", [
  192. ...routerArrays,
  193. ...usePermissionStoreHook().flatteningRoutes.filter(
  194. v => v?.meta?.fixedTag
  195. )
  196. ]);
  197. }
  198. addPathMatch();
  199. }
  200. /** 初始化路由(`new Promise` 写法防止在异步请求中造成无限循环)*/
  201. function initRouter() {
  202. if (getConfig()?.CachingAsyncRoutes) {
  203. const key = "async-routes";
  204. const asyncRouteList = storageLocal().getItem(key) as any;
  205. if (asyncRouteList && asyncRouteList?.length > 0) {
  206. return new Promise(resolve => {
  207. handleAsyncRoutes(asyncRouteList);
  208. resolve(router);
  209. });
  210. } else {
  211. return new Promise(resolve => {
  212. getAsyncRoutes()
  213. .then(({ data }) => {
  214. handleAsyncRoutes(cloneDeep(data));
  215. storageLocal().setItem(key, data);
  216. resolve(router);
  217. })
  218. .catch(() => {
  219. handleAsyncRoutes([]);
  220. resolve(router);
  221. });
  222. });
  223. }
  224. } else {
  225. return new Promise(resolve => {
  226. getAsyncRoutes()
  227. .then(({ data }) => {
  228. handleAsyncRoutes(cloneDeep(data));
  229. resolve(router);
  230. })
  231. .catch(() => {
  232. handleAsyncRoutes([]);
  233. resolve(router);
  234. });
  235. });
  236. }
  237. }
  238. /**
  239. * 将多级嵌套路由处理成一维数组
  240. * @param routesList 传入路由
  241. * @returns 返回处理后的一维路由
  242. */
  243. function formatFlatteningRoutes(routesList: RouteRecordRaw[]) {
  244. if (routesList.length === 0) return routesList;
  245. let hierarchyList = buildHierarchyTree(routesList);
  246. for (let i = 0; i < hierarchyList.length; i++) {
  247. if (hierarchyList[i].children) {
  248. hierarchyList = hierarchyList
  249. .slice(0, i + 1)
  250. .concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
  251. }
  252. }
  253. return hierarchyList;
  254. }
  255. /**
  256. * 一维数组处理成多级嵌套数组(三级及以上的路由全部拍成二级,keep-alive 只支持到二级缓存)
  257. * https://github.com/pure-admin/vue-pure-admin/issues/67
  258. * @param routesList 处理后的一维路由菜单数组
  259. * @returns 返回将一维数组重新处理成规定路由的格式
  260. */
  261. function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
  262. if (routesList.length === 0) return routesList;
  263. const newRoutesList: RouteRecordRaw[] = [];
  264. routesList.forEach((v: RouteRecordRaw) => {
  265. if (v.path === "/") {
  266. newRoutesList.push({
  267. component: v.component,
  268. name: v.name,
  269. path: v.path,
  270. redirect: v.redirect,
  271. meta: v.meta,
  272. children: []
  273. });
  274. } else {
  275. newRoutesList[0]?.children.push({ ...v });
  276. }
  277. });
  278. return newRoutesList;
  279. }
  280. /** 处理缓存路由(添加、删除、刷新) */
  281. function handleAliveRoute({ name }: ToRouteType, mode?: string) {
  282. switch (mode) {
  283. case "add":
  284. usePermissionStoreHook().cacheOperate({
  285. mode: "add",
  286. name
  287. });
  288. break;
  289. case "delete":
  290. usePermissionStoreHook().cacheOperate({
  291. mode: "delete",
  292. name
  293. });
  294. break;
  295. case "refresh":
  296. usePermissionStoreHook().cacheOperate({
  297. mode: "refresh",
  298. name
  299. });
  300. break;
  301. default:
  302. usePermissionStoreHook().cacheOperate({
  303. mode: "delete",
  304. name
  305. });
  306. useTimeoutFn(() => {
  307. usePermissionStoreHook().cacheOperate({
  308. mode: "add",
  309. name
  310. });
  311. }, 100);
  312. }
  313. }
  314. /** 过滤后端传来的动态路由 重新生成规范路由 */
  315. function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
  316. if (!arrRoutes || !arrRoutes.length) return;
  317. const modulesRoutesKeys = Object.keys(modulesRoutes);
  318. arrRoutes.forEach((v: RouteRecordRaw) => {
  319. // 将backstage属性加入meta,标识此路由为后端返回路由
  320. v.meta.backstage = true;
  321. // 父级的redirect属性取值:如果子级存在且父级的redirect属性不存在,默认取第一个子级的path;如果子级存在且父级的redirect属性存在,取存在的redirect属性,会覆盖默认值
  322. if (v?.children && v.children.length && !v.redirect)
  323. v.redirect = v.children[0].path;
  324. // 父级的name属性取值:如果子级存在且父级的name属性不存在,默认取第一个子级的name;如果子级存在且父级的name属性存在,取存在的name属性,会覆盖默认值(注意:测试中发现父级的name不能和子级name重复,如果重复会造成重定向无效(跳转404),所以这里给父级的name起名的时候后面会自动加上`Parent`,避免重复)
  325. if (v?.children && v.children.length && !v.name)
  326. v.name = (v.children[0].name as string) + "Parent";
  327. if (v.meta?.frameSrc) {
  328. v.component = IFrame;
  329. } else {
  330. // 对后端传component组件路径和不传做兼容(如果后端传component组件路径,那么path可以随便写,如果不传,component组件路径会跟path保持一致)
  331. const index = v?.component
  332. ? modulesRoutesKeys.findIndex(ev => ev.includes(v.component as any))
  333. : modulesRoutesKeys.findIndex(ev => ev.includes(v.path));
  334. v.component = modulesRoutes[modulesRoutesKeys[index]];
  335. }
  336. if (v?.children && v.children.length) {
  337. addAsyncRoutes(v.children);
  338. }
  339. });
  340. return arrRoutes;
  341. }
  342. /** 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html */
  343. function getHistoryMode(routerHistory): RouterHistory {
  344. // len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
  345. const historyMode = routerHistory.split(",");
  346. const leftMode = historyMode[0];
  347. const rightMode = historyMode[1];
  348. // no param
  349. if (historyMode.length === 1) {
  350. if (leftMode === "hash") {
  351. return createWebHashHistory("");
  352. } else if (leftMode === "h5") {
  353. return createWebHistory("");
  354. }
  355. } //has param
  356. else if (historyMode.length === 2) {
  357. if (leftMode === "hash") {
  358. return createWebHashHistory(rightMode);
  359. } else if (leftMode === "h5") {
  360. return createWebHistory(rightMode);
  361. }
  362. }
  363. }
  364. /** 获取当前页面按钮级别的权限 */
  365. function getAuths(): Array<string> {
  366. return router.currentRoute.value.meta.auths as Array<string>;
  367. }
  368. /** 是否有按钮级别的权限(根据路由`meta`中的`auths`字段进行判断)*/
  369. function hasAuth(value: string | Array<string>): boolean {
  370. if (!value) return false;
  371. /** 从当前路由的`meta`字段里获取按钮级别的所有自定义`code`值 */
  372. const metaAuths = getAuths();
  373. if (!metaAuths) return false;
  374. const isAuths = isString(value)
  375. ? metaAuths.includes(value)
  376. : isIncludeAllChildren(value, metaAuths);
  377. return isAuths ? true : false;
  378. }
  379. function handleTopMenu(route) {
  380. if (!route) return route;
  381. if (route?.children && route.children.length > 1) {
  382. if (route.redirect) {
  383. return route.children.filter(cur => cur.path === route.redirect)[0];
  384. } else {
  385. return route.children[0];
  386. }
  387. } else {
  388. return route;
  389. }
  390. }
  391. /** 获取所有菜单中的第一个菜单(顶级菜单)*/
  392. function getTopMenu(tag = false): menuType {
  393. const topMenu = handleTopMenu(
  394. usePermissionStoreHook().wholeMenus[0]?.children?.[0]
  395. );
  396. if (tag && topMenu) {
  397. useMultiTagsStoreHook().handleTags("push", topMenu);
  398. }
  399. return topMenu;
  400. }
  401. export {
  402. hasAuth,
  403. getAuths,
  404. ascending,
  405. filterTree,
  406. initRouter,
  407. getTopMenu,
  408. addPathMatch,
  409. isOneOfArray,
  410. getHistoryMode,
  411. addAsyncRoutes,
  412. getParentPaths,
  413. findRouteByPath,
  414. handleAliveRoute,
  415. formatTwoStageRoutes,
  416. formatFlatteningRoutes,
  417. filterNoPermissionTree
  418. };