routerHelper.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 const 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. alwaysShow:
  55. route.children &&
  56. route.children.length === 1 &&
  57. (route.alwaysShow !== undefined ? route.alwaysShow : true)
  58. }
  59. // 路由地址转首字母大写驼峰,作为路由名称,适配keepAlive
  60. let data: AppRouteRecordRaw = {
  61. path: route.path,
  62. name:
  63. route.componentName && route.componentName.length > 0
  64. ? route.componentName
  65. : toCamelCase(route.path, true),
  66. redirect: route.redirect,
  67. meta: meta
  68. }
  69. //处理顶级非目录路由
  70. if (!route.children && route.parentId == 0 && route.component) {
  71. data.component = Layout
  72. data.meta = {}
  73. data.name = toCamelCase(route.path, true) + 'Parent'
  74. data.redirect = ''
  75. meta.alwaysShow = true
  76. const childrenData: AppRouteRecordRaw = {
  77. path: '',
  78. name: toCamelCase(route.path, true),
  79. redirect: route.redirect,
  80. meta: meta
  81. }
  82. const index = route?.component
  83. ? modulesRoutesKeys.findIndex((ev) => ev.includes(route.component))
  84. : modulesRoutesKeys.findIndex((ev) => ev.includes(route.path))
  85. childrenData.component = modules[modulesRoutesKeys[index]]
  86. data.children = [childrenData]
  87. } else {
  88. // 目录
  89. if (route.children) {
  90. data.component = Layout
  91. data.redirect = getRedirect(route.path, route.children)
  92. // 外链
  93. } else if (isUrl(route.path)) {
  94. data = {
  95. path: '/external-link',
  96. component: Layout,
  97. meta: {
  98. name: route.name
  99. },
  100. children: [data]
  101. } as AppRouteRecordRaw
  102. // 菜单
  103. } else {
  104. // 对后端传component组件路径和不传做兼容(如果后端传component组件路径,那么path可以随便写,如果不传,component组件路径会根path保持一致)
  105. const index = route?.component
  106. ? modulesRoutesKeys.findIndex((ev) => ev.includes(route.component))
  107. : modulesRoutesKeys.findIndex((ev) => ev.includes(route.path))
  108. data.component = modules[modulesRoutesKeys[index]]
  109. }
  110. if (route.children) {
  111. data.children = generateRoute(route.children)
  112. }
  113. }
  114. res.push(data as AppRouteRecordRaw)
  115. }
  116. return res
  117. }
  118. export const getRedirect = (parentPath: string, children: AppCustomRouteRecordRaw[]) => {
  119. if (!children || children.length == 0) {
  120. return parentPath
  121. }
  122. const path = generateRoutePath(parentPath, children[0].path)
  123. // 递归子节点
  124. if (children[0].children) return getRedirect(path, children[0].children)
  125. }
  126. const generateRoutePath = (parentPath: string, path: string) => {
  127. if (parentPath.endsWith('/')) {
  128. parentPath = parentPath.slice(0, -1) // 移除默认的 /
  129. }
  130. if (!path.startsWith('/')) {
  131. path = '/' + path
  132. }
  133. return parentPath + path
  134. }
  135. export const pathResolve = (parentPath: string, path: string) => {
  136. if (isUrl(path)) return path
  137. const childPath = path.startsWith('/') || !path ? path : `/${path}`
  138. return `${parentPath}${childPath}`.replace(/\/\//g, '/')
  139. }
  140. // 路由降级
  141. export const flatMultiLevelRoutes = (routes: AppRouteRecordRaw[]) => {
  142. const modules: AppRouteRecordRaw[] = cloneDeep(routes)
  143. for (let index = 0; index < modules.length; index++) {
  144. const route = modules[index]
  145. if (!isMultipleRoute(route)) {
  146. continue
  147. }
  148. promoteRouteLevel(route)
  149. }
  150. return modules
  151. }
  152. // 层级是否大于2
  153. const isMultipleRoute = (route: AppRouteRecordRaw) => {
  154. if (!route || !Reflect.has(route, 'children') || !route.children?.length) {
  155. return false
  156. }
  157. const children = route.children
  158. let flag = false
  159. for (let index = 0; index < children.length; index++) {
  160. const child = children[index]
  161. if (child.children?.length) {
  162. flag = true
  163. break
  164. }
  165. }
  166. return flag
  167. }
  168. // 生成二级路由
  169. const promoteRouteLevel = (route: AppRouteRecordRaw) => {
  170. let router: Router | null = createRouter({
  171. routes: [route as RouteRecordRaw],
  172. history: createWebHashHistory()
  173. })
  174. const routes = router.getRoutes()
  175. addToChildren(routes, route.children || [], route)
  176. router = null
  177. route.children = route.children?.map((item) => omit(item, 'children'))
  178. }
  179. // 添加所有子菜单
  180. const addToChildren = (
  181. routes: RouteRecordNormalized[],
  182. children: AppRouteRecordRaw[],
  183. routeModule: AppRouteRecordRaw
  184. ) => {
  185. for (let index = 0; index < children.length; index++) {
  186. const child = children[index]
  187. const route = routes.find((item) => item.name === child.name)
  188. if (!route) {
  189. continue
  190. }
  191. routeModule.children = routeModule.children || []
  192. if (!routeModule.children.find((item) => item.name === route.name)) {
  193. routeModule.children?.push(route as unknown as AppRouteRecordRaw)
  194. }
  195. if (child.children?.length) {
  196. addToChildren(routes, child.children, routeModule)
  197. }
  198. }
  199. }
  200. const toCamelCase = (str: string, upperCaseFirst: boolean) => {
  201. str = (str || '')
  202. .replace(/-(.)/g, function (group1: string) {
  203. return group1.toUpperCase()
  204. })
  205. .replaceAll('-', '')
  206. if (upperCaseFirst && str) {
  207. str = str.charAt(0).toUpperCase() + str.slice(1)
  208. }
  209. return str
  210. }