routerHelper.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 > 0 &&
  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. hidden: meta.hidden,
  99. }
  100. data.name = toCamelCase(route.path, true) + 'Parent'
  101. data.redirect = ''
  102. meta.alwaysShow = true
  103. const childrenData: AppRouteRecordRaw = {
  104. path: '',
  105. name:
  106. route.componentName && route.componentName.length > 0
  107. ? route.componentName
  108. : toCamelCase(route.path, true),
  109. redirect: route.redirect,
  110. meta: meta
  111. }
  112. const index = route?.component
  113. ? modulesRoutesKeys.findIndex((ev) => ev.includes(route.component))
  114. : modulesRoutesKeys.findIndex((ev) => ev.includes(route.path))
  115. childrenData.component = modules[modulesRoutesKeys[index]]
  116. data.children = [childrenData]
  117. } else {
  118. // 目录
  119. if (route.children?.length) {
  120. data.component = Layout
  121. data.redirect = getRedirect(route.path, route.children)
  122. // 外链
  123. } else if (isUrl(route.path)) {
  124. data = {
  125. path: '/external-link',
  126. component: Layout,
  127. meta: {
  128. name: route.name
  129. },
  130. children: [data]
  131. } as AppRouteRecordRaw
  132. // 菜单
  133. } else {
  134. // 对后端传component组件路径和不传做兼容(如果后端传component组件路径,那么path可以随便写,如果不传,component组件路径会根path保持一致)
  135. const index = route?.component
  136. ? modulesRoutesKeys.findIndex((ev) => ev.includes(route.component))
  137. : modulesRoutesKeys.findIndex((ev) => ev.includes(route.path))
  138. data.component = modules[modulesRoutesKeys[index]]
  139. }
  140. if (route.children) {
  141. data.children = generateRoute(route.children)
  142. }
  143. }
  144. res.push(data as AppRouteRecordRaw)
  145. }
  146. return res
  147. }
  148. export const getRedirect = (parentPath: string, children: AppCustomRouteRecordRaw[]) => {
  149. if (!children || children.length == 0) {
  150. return parentPath
  151. }
  152. const path = generateRoutePath(parentPath, children[0].path)
  153. // 递归子节点
  154. if (children[0].children) return getRedirect(path, children[0].children)
  155. }
  156. const generateRoutePath = (parentPath: string, path: string) => {
  157. if (parentPath.endsWith('/')) {
  158. parentPath = parentPath.slice(0, -1) // 移除默认的 /
  159. }
  160. if (!path.startsWith('/')) {
  161. path = '/' + path
  162. }
  163. return parentPath + path
  164. }
  165. export const pathResolve = (parentPath: string, path: string) => {
  166. if (isUrl(path)) return path
  167. const childPath = path.startsWith('/') || !path ? path : `/${path}`
  168. return `${parentPath}${childPath}`.replace(/\/\//g, '/')
  169. }
  170. // 路由降级
  171. export const flatMultiLevelRoutes = (routes: AppRouteRecordRaw[]) => {
  172. const modules: AppRouteRecordRaw[] = cloneDeep(routes)
  173. for (let index = 0; index < modules.length; index++) {
  174. const route = modules[index]
  175. if (!isMultipleRoute(route)) {
  176. continue
  177. }
  178. promoteRouteLevel(route)
  179. }
  180. return modules
  181. }
  182. // 层级是否大于2
  183. const isMultipleRoute = (route: AppRouteRecordRaw) => {
  184. if (!route || !Reflect.has(route, 'children') || !route.children?.length) {
  185. return false
  186. }
  187. const children = route.children
  188. let flag = false
  189. for (let index = 0; index < children.length; index++) {
  190. const child = children[index]
  191. if (child.children?.length) {
  192. flag = true
  193. break
  194. }
  195. }
  196. return flag
  197. }
  198. // 生成二级路由
  199. const promoteRouteLevel = (route: AppRouteRecordRaw) => {
  200. let router: Router | null = createRouter({
  201. routes: [route as RouteRecordRaw],
  202. history: createWebHashHistory()
  203. })
  204. const routes = router.getRoutes()
  205. addToChildren(routes, route.children || [], route)
  206. router = null
  207. route.children = route.children?.map((item) => omit(item, 'children'))
  208. }
  209. // 添加所有子菜单
  210. const addToChildren = (
  211. routes: RouteRecordNormalized[],
  212. children: AppRouteRecordRaw[],
  213. routeModule: AppRouteRecordRaw
  214. ) => {
  215. for (let index = 0; index < children.length; index++) {
  216. const child = children[index]
  217. const route = routes.find((item) => item.name === child.name)
  218. if (!route) {
  219. continue
  220. }
  221. routeModule.children = routeModule.children || []
  222. if (!routeModule.children.find((item) => item.name === route.name)) {
  223. routeModule.children?.push(route as unknown as AppRouteRecordRaw)
  224. }
  225. if (child.children?.length) {
  226. addToChildren(routes, child.children, routeModule)
  227. }
  228. }
  229. }
  230. const toCamelCase = (str: string, upperCaseFirst: boolean) => {
  231. str = (str || '')
  232. .replace(/-(.)/g, function (group1: string) {
  233. return group1.toUpperCase()
  234. })
  235. .replaceAll('-', '')
  236. if (upperCaseFirst && str) {
  237. str = str.charAt(0).toUpperCase() + str.slice(1)
  238. }
  239. return str
  240. }