keepAlive.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { defineStore } from 'pinia'
  2. export type Route = {
  3. name: string
  4. fullPath: string
  5. }
  6. export const useKeepAliveStore = defineStore('keepAlive', () => {
  7. const savedRoutes = ref<Route[]>(
  8. JSON.parse(sessionStorage.getItem('savedRoutes') ?? '[]')
  9. )
  10. const saveRoute = ({ name, fullPath }: Route) => {
  11. const index = savedRoutes.value.findIndex(
  12. savedRoute => savedRoute.name === name
  13. )
  14. if (index > -1) {
  15. savedRoutes.value[index] = { name, fullPath }
  16. } else {
  17. savedRoutes.value.push({ name, fullPath })
  18. }
  19. sessionStorage.setItem('savedRoutes', JSON.stringify(savedRoutes.value))
  20. }
  21. const cachedViews = ref<string[]>([])
  22. const addCachedView = (viewName: string) => {
  23. cachedViews.value.includes(viewName) || cachedViews.value.push(viewName)
  24. }
  25. const addCachedViewAll = (views: string[]) => {
  26. views.forEach(view => addCachedView(view))
  27. }
  28. const delCachedView = (viewName: string) => {
  29. const index = cachedViews.value.indexOf(viewName)
  30. index > -1 && cachedViews.value.splice(index, 1)
  31. }
  32. const delCachedViewUntil = (viewName: string) => {
  33. while (
  34. cachedViews.value.length &&
  35. cachedViews.value[cachedViews.value.length - 1] !== viewName
  36. ) {
  37. cachedViews.value.pop()
  38. }
  39. }
  40. const delCachedViewAll = () => {
  41. cachedViews.value = []
  42. }
  43. return {
  44. savedRoutes,
  45. saveRoute,
  46. cachedViews,
  47. addCachedView,
  48. addCachedViewAll,
  49. delCachedView,
  50. delCachedViewAll,
  51. delCachedViewUntil,
  52. }
  53. })