routerHelper.ts 8.0 KB

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