useGlobalCache.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { useStyleInject } from '../StyleContext';
  2. import useHMR from './useHMR';
  3. import { onBeforeUnmount, watch, watchEffect, shallowRef } from 'vue';
  4. export default function useClientCache(prefix, keyPath, cacheFn, onCacheRemove) {
  5. const styleContext = useStyleInject();
  6. const fullPathStr = shallowRef('');
  7. const res = shallowRef();
  8. watchEffect(() => {
  9. fullPathStr.value = [prefix, ...keyPath.value].join('%');
  10. });
  11. const HMRUpdate = useHMR();
  12. const clearCache = pathStr => {
  13. styleContext.value.cache.update(pathStr, prevCache => {
  14. const [times = 0, cache] = prevCache || [];
  15. const nextCount = times - 1;
  16. if (nextCount === 0) {
  17. onCacheRemove === null || onCacheRemove === void 0 ? void 0 : onCacheRemove(cache, false);
  18. return null;
  19. }
  20. return [times - 1, cache];
  21. });
  22. };
  23. watch(fullPathStr, (newStr, oldStr) => {
  24. if (oldStr) clearCache(oldStr);
  25. // Create cache
  26. styleContext.value.cache.update(newStr, prevCache => {
  27. const [times = 0, cache] = prevCache || [];
  28. // HMR should always ignore cache since developer may change it
  29. let tmpCache = cache;
  30. if (process.env.NODE_ENV !== 'production' && cache && HMRUpdate) {
  31. onCacheRemove === null || onCacheRemove === void 0 ? void 0 : onCacheRemove(tmpCache, HMRUpdate);
  32. tmpCache = null;
  33. }
  34. const mergedCache = tmpCache || cacheFn();
  35. return [times + 1, mergedCache];
  36. });
  37. res.value = styleContext.value.cache.get(fullPathStr.value)[1];
  38. }, {
  39. immediate: true
  40. });
  41. onBeforeUnmount(() => {
  42. clearCache(fullPathStr.value);
  43. });
  44. return res;
  45. }