utils.ts 13 KB

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