utils.ts 15 KB

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