routerHelper.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
  2. import type { Router, RouteLocationNormalized, RouteRecordNormalized } from 'vue-router'
  3. import { isUrl } from '@/utils/is'
  4. import { omit, cloneDeep } from 'lodash-es'
  5. const modules = import.meta.glob('../views/**/*.{vue,tsx}')
  6. /* Layout */
  7. export const Layout = () => import('@/layout/Layout.vue')
  8. export const getParentLayout = () => {
  9. return () =>
  10. new Promise((resolve) => {
  11. resolve({
  12. name: 'ParentLayout'
  13. })
  14. })
  15. }
  16. // 按照路由中meta下的rank等级升序来排序路由
  17. export function ascending(arr: any[]) {
  18. arr.forEach((v) => {
  19. if (v?.meta?.rank === null) v.meta.rank = undefined
  20. if (v?.meta?.rank === 0) {
  21. if (v.name !== 'home' && v.path !== '/') {
  22. console.warn('rank only the home page can be 0')
  23. }
  24. }
  25. })
  26. return arr.sort((a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
  27. return a?.meta?.rank - b?.meta?.rank
  28. })
  29. }
  30. export const getRawRoute = (route: RouteLocationNormalized): RouteLocationNormalized => {
  31. if (!route) return route
  32. const { matched, ...opt } = route
  33. return {
  34. ...opt,
  35. matched: (matched
  36. ? matched.map((item) => ({
  37. meta: item.meta,
  38. name: item.name,
  39. path: item.path
  40. }))
  41. : undefined) as RouteRecordNormalized[]
  42. }
  43. }
  44. // 后端控制路由生成
  45. export const generateRoute = (routes: AppCustomRouteRecordRaw[]): AppRouteRecordRaw[] => {
  46. const res: AppRouteRecordRaw[] = []
  47. const modulesRoutesKeys = Object.keys(modules)
  48. for (const route of routes) {
  49. const meta = {
  50. title: route.name,
  51. icon: route.icon,
  52. hidden: !route.visible,
  53. noCache: !route.keepAlive
  54. }
  55. // 路由地址转首字母大写驼峰,作为路由名称,适配keepAlive
  56. let data: AppRouteRecordRaw = {
  57. path: route.path,
  58. name: toCamelCase(route.path, true),
  59. redirect: route.redirect,
  60. meta: meta
  61. }
  62. // 目录
  63. if (route.children) {
  64. data.component = Layout
  65. data.redirect = getRedirect(route.path, route.children)
  66. // 外链
  67. } else if (isUrl(route.path)) {
  68. data = {
  69. path: '/external-link',
  70. component: Layout,
  71. meta: {
  72. name: route.name
  73. },
  74. children: [data]
  75. } as AppRouteRecordRaw
  76. // 菜单
  77. } else {
  78. // 对后端传component组件路径和不传做兼容(如果后端传component组件路径,那么path可以随便写,如果不传,component组件路径会根path保持一致)
  79. const index = route?.component
  80. ? modulesRoutesKeys.findIndex((ev) => ev.includes(route.component))
  81. : modulesRoutesKeys.findIndex((ev) => ev.includes(route.path))
  82. data.component = modules[modulesRoutesKeys[index]]
  83. }
  84. if (route.children) {
  85. data.children = generateRoute(route.children)
  86. }
  87. res.push(data)
  88. }
  89. return res
  90. }
  91. export const getRedirect = (parentPath: string, children: AppCustomRouteRecordRaw[]) => {
  92. if (!children || children.length == 0) {
  93. return parentPath
  94. }
  95. const path = generateRoutePath(parentPath, children[0].path)
  96. // 递归子节点
  97. if (children[0].children) return getRedirect(path, children[0].children)
  98. }
  99. const generateRoutePath = (parentPath: string, path: string) => {
  100. if (parentPath.endsWith('/')) {
  101. parentPath = parentPath.slice(0, -1) // 移除默认的 /
  102. }
  103. if (!path.startsWith('/')) {
  104. path = '/' + path
  105. }
  106. return parentPath + path
  107. }
  108. export const pathResolve = (parentPath: string, path: string) => {
  109. if (isUrl(path)) return path
  110. const childPath = path.startsWith('/') || !path ? path : `/${path}`
  111. return `${parentPath}${childPath}`.replace(/\/\//g, '/')
  112. }
  113. // 路由降级
  114. export const flatMultiLevelRoutes = (routes: AppRouteRecordRaw[]) => {
  115. const modules: AppRouteRecordRaw[] = cloneDeep(routes)
  116. for (let index = 0; index < modules.length; index++) {
  117. const route = modules[index]
  118. if (!isMultipleRoute(route)) {
  119. continue
  120. }
  121. promoteRouteLevel(route)
  122. }
  123. return modules
  124. }
  125. // 层级是否大于2
  126. const isMultipleRoute = (route: AppRouteRecordRaw) => {
  127. if (!route || !Reflect.has(route, 'children') || !route.children?.length) {
  128. return false
  129. }
  130. const children = route.children
  131. let flag = false
  132. for (let index = 0; index < children.length; index++) {
  133. const child = children[index]
  134. if (child.children?.length) {
  135. flag = true
  136. break
  137. }
  138. }
  139. return flag
  140. }
  141. // 生成二级路由
  142. const promoteRouteLevel = (route: AppRouteRecordRaw) => {
  143. let router: Router | null = createRouter({
  144. routes: [route as RouteRecordRaw],
  145. history: createWebHashHistory()
  146. })
  147. const routes = router.getRoutes()
  148. addToChildren(routes, route.children || [], route)
  149. router = null
  150. route.children = route.children?.map((item) => omit(item, 'children'))
  151. }
  152. // 添加所有子菜单
  153. const addToChildren = (
  154. routes: RouteRecordNormalized[],
  155. children: AppRouteRecordRaw[],
  156. routeModule: AppRouteRecordRaw
  157. ) => {
  158. for (let index = 0; index < children.length; index++) {
  159. const child = children[index]
  160. const route = routes.find((item) => item.name === child.name)
  161. if (!route) {
  162. continue
  163. }
  164. routeModule.children = routeModule.children || []
  165. if (!routeModule.children.find((item) => item.name === route.name)) {
  166. routeModule.children?.push(route as unknown as AppRouteRecordRaw)
  167. }
  168. if (child.children?.length) {
  169. addToChildren(routes, child.children, routeModule)
  170. }
  171. }
  172. }
  173. function toCamelCase(str: string, upperCaseFirst: boolean) {
  174. str = (str || '').toLowerCase().replace(/-(.)/g, function (group1: string) {
  175. return group1.toUpperCase()
  176. })
  177. if (upperCaseFirst && str) {
  178. str = str.charAt(0).toUpperCase() + str.slice(1)
  179. }
  180. return str
  181. }