| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import { shallowRef, computed } from 'vue'
- /**
- * 本地存储类(基础版)
- */
- export default class <T> {
- constructor(storage: Storage, key: string, value: T) {
- this.storage = storage
- this.storageKey = key
- this.source = value
- this.state = shallowRef(value)
- const storageValue = this.storage.getItem(this.storageKey)
- if (storageValue) {
- this.state.value = JSON.parse(storageValue)
- }
- }
- private readonly source // 原始数据
- private readonly storage
- readonly storageKey
- private state
- /**
- * 获取数据
- * @returns
- */
- getValue() {
- return this.state.value
- }
- /**
- * 更新数据
- * @param value
- */
- setValue(value: T) {
- if (value === undefined || value === null) {
- this.storage.removeItem(this.storageKey)
- } else {
- const storageValue = JSON.stringify(value) // 注意数值长度过长会被自动转换为 String 类型
- this.storage.setItem(this.storageKey, storageValue)
- }
- this.state.value = value
- }
- /**
- * 获取响应数据
- * @returns
- */
- getRef() {
- return computed({
- get: () => this.getValue(),
- set: (val) => this.setValue(val)
- })
- }
- /**
- * 重置数据
- */
- reset() {
- this.state.value = this.source
- }
- }
|