routerTravelStore.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { defineStore } from 'pinia'
  2. import { ref, nextTick, computed } from 'vue'
  3. import { RouteRecordRaw } from 'vue-router'
  4. import router, { routes } from '@/router'
  5. import { useAppRouter } from '@/store/router'
  6. export const useRouterTravelStore = defineStore('routerTravelStore', () => {
  7. const appRouter = useAppRouter()
  8. const history = ref<RouteRecordRaw[]>([])
  9. const currentRoute = ref<RouteRecordRaw>()
  10. const currenRouteIndex = ref<number>(0)
  11. const keyCount = ref<number>(0)
  12. const init = () => {
  13. push(JSON.parse(JSON.stringify(routes[1].children[0])))
  14. currentRoute.value = history.value[0]
  15. }
  16. const del = (path: string) => {
  17. const index = history.value.findIndex(item => item.path === path)
  18. if (index === currenRouteIndex.value) {
  19. currenRouteIndex.value = index - 1
  20. currentRoute.value = history.value[currenRouteIndex.value]
  21. history.value.splice(currenRouteIndex.value + 1, 1)
  22. } else {
  23. history.value.splice(index, 1)
  24. }
  25. router.push(currentRoute.value!.path)
  26. }
  27. const push = (route: RouteRecordRaw) => {
  28. const index = history.value.findIndex(item => item.path === route.path)
  29. if (index !== -1) {
  30. currenRouteIndex.value = index
  31. } else {
  32. history.value.push(route)
  33. currenRouteIndex.value = history.value.length - 1
  34. }
  35. currentRoute.value = route
  36. console.log('父节点:', appRouter.findRootRoute(route.path))
  37. }
  38. const setCurrentRoute = (route: RouteRecordRaw) => {
  39. currentRoute.value = route
  40. router.push(currentRoute.value!.path)
  41. }
  42. const closeOtherPage = () => {
  43. history.value = [JSON.parse(JSON.stringify(routes[1].children[0])), currentRoute.value]
  44. currenRouteIndex.value = history.value.length - 1
  45. }
  46. init()
  47. return {
  48. history,
  49. currentRoute,
  50. currenRouteIndex,
  51. keyCount,
  52. setCurrentRoute,
  53. push,
  54. del,
  55. closeOtherPage
  56. }
  57. }, {
  58. persist: true
  59. })