router.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { defineStore } from 'pinia'
  2. import { ConstantStore } from '@/enum/store'
  3. import { ref, computed, onMounted, watch, reactive, watchEffect } from 'vue'
  4. import RootRouter from '@/router'
  5. import { useLocalStorageState } from 'vue-hooks-plus'
  6. import { AppRouter as AppRouterEnum, Emitter } from '@/enum'
  7. import { useEmitter } from '@/hooks/index'
  8. import { useRoute } from 'vue-router'
  9. /**
  10. * 1. 获取当前路由path
  11. * 2. 从缓存中获取router, 防止刷新都丢失状态
  12. * 3. 获取navbar路由list
  13. * 3.1 根据当前的路由path 反推到最顶级父元素 将其置为常亮
  14. * 4. 每次点击navbar的路由的时候,将对应的sider第一项展开
  15. */
  16. const emitter = useEmitter()
  17. const initAppRouterState: Router.RouterRecords = {
  18. navbar: {
  19. route: [],
  20. selectPath: ''
  21. },
  22. sider: {
  23. route: [],
  24. selectPath: '',
  25. openKeys: []
  26. }
  27. }
  28. export const useAppRouter = defineStore(ConstantStore.ROUTER, () => {
  29. let appRouter = reactive<Router.RouterRecords>(initAppRouterState)
  30. const route = useRoute()
  31. const [appRouterState, setAppRouterState] = useLocalStorageState<Router.RouterRecords>(AppRouterEnum.ROUTER, {
  32. defaultValue: initAppRouterState
  33. })
  34. const siderRoutes = computed(() => RootRouter.getRoutes().find(item => item.path === appRouter.navbar!.selectPath)?.children)
  35. const initAppRouter = () => {
  36. appRouter.navbar.route = RootRouter.options.routes.map(route => {
  37. return {
  38. path: route.path,
  39. name: route.name
  40. }
  41. })
  42. appRouter.navbar.selectPath = RootRouter.options.routes[0].path
  43. appRouter.sider.route = siderRoutes.value!
  44. setAppRouterState(appRouter)
  45. }
  46. const changeNavbar = (path: string) => {
  47. RootRouter.push(path)
  48. appRouter.navbar.selectPath = path
  49. }
  50. watch(
  51. () => RootRouter.currentRoute.value.path,
  52. () => {
  53. appRouter.sider = {
  54. route: RootRouter.getRoutes().find(item => item.path === appRouter.navbar!.selectPath)?.children as Router.RoutesProps[],
  55. selectPath: RootRouter.currentRoute.value.path,
  56. openKeys: [RootRouter.currentRoute.value.matched[1].path]
  57. }
  58. setAppRouterState(appRouter)
  59. emitter.emit(Emitter.NAVBAR)
  60. }
  61. )
  62. appRouter = appRouterState.value as Router.RouterRecords
  63. if (appRouter.navbar.route.length === 0) {
  64. initAppRouter()
  65. }
  66. return {
  67. router: appRouter,
  68. changeNavbar
  69. }
  70. })