index.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { createRouter, createWebHashHistory } from 'vue-router'
  2. import { routes } from './config'
  3. import { computed, watch, watchEffect } from 'vue'
  4. import { RoutesName } from './constant'
  5. import { metas } from './constant'
  6. import { RouteRaw } from './config'
  7. export const history = createWebHashHistory()
  8. export const router = createRouter({ history, routes })
  9. export const getRouteTree = (name: RoutesName, raw: RouteRaw[] = routes): void | RouteRaw => {
  10. for (const route of raw) {
  11. if (route.name === name) {
  12. return route
  13. } else if (route.children) {
  14. const children = getRouteTree(name, route.children)
  15. if (children) {
  16. return {...route, children: [children] }
  17. }
  18. }
  19. }
  20. }
  21. export const getRouteNames = (name: RoutesName, raw: RouteRaw[] = routes): RoutesName[] => {
  22. let current = getRouteTree(name, raw)
  23. const names: RoutesName[] = []
  24. while (current) {
  25. names.push(current.name!)
  26. current = current.children && current.children[0]
  27. }
  28. return names
  29. }
  30. export const getRouteConfig = (name: RoutesName, raw: RouteRaw[] = routes): RouteRaw | void => {
  31. let current = getRouteTree(name, raw)
  32. while (current?.children && current.children[0]) {
  33. current = current.children[0]
  34. }
  35. return current
  36. }
  37. export const currentRouteNames = computed(() => getRouteNames(router.currentRoute.value.name as RoutesName, routes))
  38. export const currentLayout = computed(() => {
  39. const names = currentRouteNames.value
  40. const layoutNames = [RoutesName.fuseEditSwitch, RoutesName.show, RoutesName.error, RoutesName.sceneEdit, RoutesName.signModel] as const
  41. return layoutNames.find(name => names.includes(name))
  42. })
  43. export const currentMeta = computed(() => {
  44. const currentName = router.currentRoute.value.name
  45. if (currentName && currentName in metas) {
  46. return (metas as any )[currentName] as ((typeof metas)[keyof typeof metas])
  47. }
  48. })
  49. let timeout: any
  50. watch(currentLayout, () => {
  51. clearTimeout(timeout)
  52. timeout = setTimeout(() => {
  53. if (!currentLayout.value) {
  54. router.replace({ name: RoutesName.fireInfo })
  55. }
  56. }, 100)
  57. })
  58. export * from './config'
  59. export * from './constant'
  60. export default router