Skip to content

useStorage

通用存储 Hook,支持 localStorage、sessionStorage 或自定义存储适配器。

函数签名

typescript
function useStorage<T>(
  key: string,
  defaultValue: T,
  storage: StorageAdapter,
  options?: StorageOptions<T>
): [Ref<T>, (value: T) => void, () => void]

interface StorageAdapter {
  getItem(key: string): string | null
  setItem(key: string, value: string): void
  removeItem(key: string): void
}

interface StorageOptions<T> {
  prefix?: string
  serializer?: {
    serialize: (value: T) => string
    deserialize: (value: string) => T
  }
}

参数

参数名类型必填默认值说明
keystring-存储键名
defaultValueT-默认值
storageStorageAdapter-存储适配器对象
options.prefixstring''键名前缀
options.serializerobjectJSON.stringify/parse自定义序列化器

返回值

类型说明
[Ref<T>, (value: T) => void, () => void]返回元组:[响应式值, 设置函数, 删除函数]

工作原理

  1. 接收任意符合 StorageAdapter 接口的存储对象
  2. 使用适配器的 getItem/setItem/removeItem 方法操作存储
  3. 提供与 useLocalStorage/useSessionStorage 相同的 API
  4. 支持自定义存储后端(如 IndexedDB、内存缓存等)

存储适配器可以是:

  • window.localStorage
  • window.sessionStorage
  • 自定义实现(如内存存储、文件存储等)

通用的存储抽象,useLocalStorageuseSessionStorage 都基于此实现。