cache.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import type { Preference } from '@vben-core/typings';
  2. class PreferenceCache {
  3. cachePrefix: string;
  4. constructor(cachePrefix: string) {
  5. this.cachePrefix = cachePrefix;
  6. }
  7. /**
  8. * 从 localStorage 中获取偏好设置
  9. * @returns 返回从 localStorage 中获取的偏好设置,如果没有获取到,则返回默认偏好设置。
  10. */
  11. get(defaultValue: Preference): Preference {
  12. let cache = defaultValue;
  13. try {
  14. cache = JSON.parse(localStorage.getItem(this.getCacheKey()) || '');
  15. } catch {
  16. return defaultValue;
  17. }
  18. return cache;
  19. }
  20. /**
  21. * 获取偏好设置的缓存键
  22. */
  23. getCacheKey(name: string = 'preference') {
  24. return `__${this.cachePrefix}-${name}__`;
  25. }
  26. /**
  27. * 从 localStorage 中移除偏好设置
  28. */
  29. remove() {
  30. localStorage.removeItem(this.getCacheKey());
  31. localStorage.removeItem(this.getCacheKey('locale'));
  32. localStorage.removeItem(this.getCacheKey('theme'));
  33. }
  34. /**
  35. * 将当前偏好设置持久化到 localStorage
  36. */
  37. set(preference: Preference) {
  38. localStorage.setItem(this.getCacheKey(), JSON.stringify(preference));
  39. // 额外存储一份主题、语言
  40. localStorage.setItem(this.getCacheKey('locale'), preference.locale);
  41. localStorage.setItem(this.getCacheKey('theme'), preference.theme);
  42. }
  43. /**
  44. * 设置偏好设置的缓存前缀
  45. * @param prefix - 前缀
  46. */
  47. setCachePrefix(prefix: string) {
  48. this.cachePrefix = prefix;
  49. }
  50. }
  51. export type PreferenceCacheType = PreferenceCache;
  52. export { PreferenceCache };