utils.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. /** 初始化路由 */
  174. function initRouter() {
  175. return new Promise(resolve => {
  176. if (getConfig()?.CachingAsyncRoutes) {
  177. // 开启动态路由缓存本地sessionStorage
  178. const key = "async-routes";
  179. const asyncRouteList = storageSession.getItem(key) as any;
  180. if (asyncRouteList?.length > 0) {
  181. handleAsyncRoutes(asyncRouteList);
  182. } else {
  183. getAsyncRoutes().then(({ data }) => {
  184. handleAsyncRoutes(data);
  185. storageSession.setItem(key, data);
  186. });
  187. }
  188. resolve(router);
  189. } else {
  190. getAsyncRoutes().then(({ data }) => {
  191. handleAsyncRoutes(data);
  192. resolve(router);
  193. });
  194. }
  195. });
  196. }
  197. /**
  198. * 将多级嵌套路由处理成一维数组
  199. * @param routesList 传入路由
  200. * @returns 返回处理后的一维路由
  201. */
  202. function formatFlatteningRoutes(routesList: RouteRecordRaw[]) {
  203. if (routesList.length === 0) return routesList;
  204. let hierarchyList = buildHierarchyTree(routesList);
  205. for (let i = 0; i < hierarchyList.length; i++) {
  206. if (hierarchyList[i].children) {
  207. hierarchyList = hierarchyList
  208. .slice(0, i + 1)
  209. .concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
  210. }
  211. }
  212. return hierarchyList;
  213. }
  214. /**
  215. * 一维数组处理成多级嵌套数组(三级及以上的路由全部拍成二级,keep-alive 只支持到二级缓存)
  216. * https://github.com/xiaoxian521/vue-pure-admin/issues/67
  217. * @param routesList 处理后的一维路由菜单数组
  218. * @returns 返回将一维数组重新处理成规定路由的格式
  219. */
  220. function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
  221. if (routesList.length === 0) return routesList;
  222. const newRoutesList: RouteRecordRaw[] = [];
  223. routesList.forEach((v: RouteRecordRaw) => {
  224. if (v.path === "/") {
  225. newRoutesList.push({
  226. component: v.component,
  227. name: v.name,
  228. path: v.path,
  229. redirect: v.redirect,
  230. meta: v.meta,
  231. children: []
  232. });
  233. } else {
  234. newRoutesList[0].children.push({ ...v });
  235. }
  236. });
  237. return newRoutesList;
  238. }
  239. /** 处理缓存路由(添加、删除、刷新) */
  240. function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) {
  241. switch (mode) {
  242. case "add":
  243. matched.forEach(v => {
  244. usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
  245. });
  246. break;
  247. case "delete":
  248. usePermissionStoreHook().cacheOperate({
  249. mode: "delete",
  250. name: matched[matched.length - 1].name
  251. });
  252. break;
  253. default:
  254. usePermissionStoreHook().cacheOperate({
  255. mode: "delete",
  256. name: matched[matched.length - 1].name
  257. });
  258. useTimeoutFn(() => {
  259. matched.forEach(v => {
  260. usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
  261. });
  262. }, 100);
  263. }
  264. }
  265. /** 过滤后端传来的动态路由 重新生成规范路由 */
  266. function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
  267. if (!arrRoutes || !arrRoutes.length) return;
  268. const modulesRoutesKeys = Object.keys(modulesRoutes);
  269. arrRoutes.forEach((v: RouteRecordRaw) => {
  270. // 将backstage属性加入meta,标识此路由为后端返回路由
  271. v.meta.backstage = true;
  272. // 父级的redirect属性取值:如果子级存在且父级的redirect属性不存在,默认取第一个子级的path;如果子级存在且父级的redirect属性存在,取存在的redirect属性,会覆盖默认值
  273. if (v?.children && v.children.length && !v.redirect)
  274. v.redirect = v.children[0].path;
  275. // 父级的name属性取值:如果子级存在且父级的name属性不存在,默认取第一个子级的name;如果子级存在且父级的name属性存在,取存在的name属性,会覆盖默认值(注意:测试中发现父级的name不能和子级name重复,如果重复会造成重定向无效(跳转404),所以这里给父级的name起名的时候后面会自动加上`Parent`,避免重复)
  276. if (v?.children && v.children.length && !v.name)
  277. v.name = (v.children[0].name as string) + "Parent";
  278. if (v.meta?.frameSrc) {
  279. v.component = IFrame;
  280. } else {
  281. // 对后端传component组件路径和不传做兼容(如果后端传component组件路径,那么path可以随便写,如果不传,component组件路径会跟path保持一致)
  282. const index = v?.component
  283. ? modulesRoutesKeys.findIndex(ev => ev.includes(v.component as any))
  284. : modulesRoutesKeys.findIndex(ev => ev.includes(v.path));
  285. v.component = modulesRoutes[modulesRoutesKeys[index]];
  286. }
  287. if (v?.children && v.children.length) {
  288. addAsyncRoutes(v.children);
  289. }
  290. });
  291. return arrRoutes;
  292. }
  293. /** 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html */
  294. function getHistoryMode(): RouterHistory {
  295. const routerHistory = loadEnv().VITE_ROUTER_HISTORY;
  296. // len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
  297. const historyMode = routerHistory.split(",");
  298. const leftMode = historyMode[0];
  299. const rightMode = historyMode[1];
  300. // no param
  301. if (historyMode.length === 1) {
  302. if (leftMode === "hash") {
  303. return createWebHashHistory("");
  304. } else if (leftMode === "h5") {
  305. return createWebHistory("");
  306. }
  307. } //has param
  308. else if (historyMode.length === 2) {
  309. if (leftMode === "hash") {
  310. return createWebHashHistory(rightMode);
  311. } else if (leftMode === "h5") {
  312. return createWebHistory(rightMode);
  313. }
  314. }
  315. }
  316. /** 获取当前页面按钮级别的权限 */
  317. function getAuths(): Array<string> {
  318. return router.currentRoute.value.meta.auths as Array<string>;
  319. }
  320. /** 是否有按钮级别的权限 */
  321. function hasAuth(value: string | Array<string>): boolean {
  322. if (!value) return false;
  323. /** 从当前路由的`meta`字段里获取按钮级别的所有自定义`code`值 */
  324. const metaAuths = getAuths();
  325. const isAuths = isString(value)
  326. ? metaAuths.includes(value)
  327. : isIncludeAllChildren(value, metaAuths);
  328. return isAuths ? true : false;
  329. }
  330. export {
  331. hasAuth,
  332. getAuths,
  333. ascending,
  334. filterTree,
  335. initRouter,
  336. isOneOfArray,
  337. getHistoryMode,
  338. addAsyncRoutes,
  339. delAliveRoutes,
  340. getParentPaths,
  341. findRouteByPath,
  342. handleAliveRoute,
  343. formatTwoStageRoutes,
  344. formatFlatteningRoutes,
  345. filterNoPermissionTree
  346. };