routerHelper.ts 6.5 KB

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