routerHelper.ts 7.2 KB

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