useCache.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { computed, ref, unref, ComponentInternalInstance, getCurrentInstance } from 'vue'
  2. import { tagsViewStore, PAGE_LAYOUT_KEY } from '_@/store/modules/tagsView'
  3. import { useRouter } from 'vue-router'
  4. function tryTsxEmit<T extends any = ComponentInternalInstance>(
  5. fn: (_instance: T) => Promise<void> | void
  6. ) {
  7. const instance = getCurrentInstance() as any
  8. instance && fn.call(null, instance)
  9. }
  10. const ParentLayoutName = 'ParentLayout'
  11. export function useCache(isPage: boolean) {
  12. const name = ref('')
  13. const { currentRoute } = useRouter()
  14. tryTsxEmit((instance) => {
  15. const routeName = instance.type.name
  16. if (routeName && ![ParentLayoutName].includes(routeName)) {
  17. name.value = routeName
  18. } else {
  19. const matched = currentRoute.value.matched
  20. const len = matched.length
  21. if (len < 2) return
  22. name.value = matched[len - 2].name as string
  23. }
  24. })
  25. const getCaches = computed((): string[] => {
  26. const cached = tagsViewStore.cachedViews
  27. if (isPage) {
  28. // page Layout
  29. // not parent layout
  30. return (cached as any).get(PAGE_LAYOUT_KEY) || []
  31. }
  32. const cacheSet = new Set<string>()
  33. cacheSet.add(unref(name))
  34. const list = (cached as any).get(unref(name))
  35. if (!list) {
  36. return Array.from(cacheSet)
  37. }
  38. (list as string[]).forEach((item: string) => {
  39. cacheSet.add(item)
  40. })
  41. return Array.from(cacheSet)
  42. })
  43. return { getCaches }
  44. }