utils.ts 11 KB

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