base.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { shallowRef, computed } from 'vue'
  2. /**
  3. * 本地存储类(基础版)
  4. */
  5. export default class <T> {
  6. constructor(storage: Storage, key: string, value: T) {
  7. this.storage = storage
  8. this.storageKey = key
  9. this.source = value
  10. this.state = shallowRef(value)
  11. const storageValue = this.storage.getItem(this.storageKey)
  12. if (storageValue) {
  13. this.state.value = JSON.parse(storageValue)
  14. }
  15. }
  16. private readonly source // 原始数据
  17. private readonly storage
  18. readonly storageKey
  19. private state
  20. /**
  21. * 获取数据
  22. * @returns
  23. */
  24. getValue() {
  25. return this.state.value
  26. }
  27. /**
  28. * 更新数据
  29. * @param value
  30. */
  31. setValue(value: T) {
  32. if (value === undefined || value === null) {
  33. this.storage.removeItem(this.storageKey)
  34. } else {
  35. const storageValue = JSON.stringify(value) // 注意数值长度过长会被自动转换为 String 类型
  36. this.storage.setItem(this.storageKey, storageValue)
  37. }
  38. this.state.value = value
  39. }
  40. /**
  41. * 获取响应数据
  42. * @returns
  43. */
  44. getRef() {
  45. return computed({
  46. get: () => this.getValue(),
  47. set: (val) => this.setValue(val)
  48. })
  49. }
  50. /**
  51. * 重置数据
  52. */
  53. reset() {
  54. this.state.value = this.source
  55. }
  56. }