routerHelper.ts 7.9 KB

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