utils.ts 12 KB

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