useGlobalCache.js 1.8 KB

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