utils.ts 12 KB

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