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
}
}参数
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
key | string | 是 | - | 存储键名 |
defaultValue | T | 是 | - | 默认值 |
storage | StorageAdapter | 是 | - | 存储适配器对象 |
options.prefix | string | 否 | '' | 键名前缀 |
options.serializer | object | 否 | JSON.stringify/parse | 自定义序列化器 |
返回值
| 类型 | 说明 |
|---|---|
[Ref<T>, (value: T) => void, () => void] | 返回元组:[响应式值, 设置函数, 删除函数] |
工作原理
- 接收任意符合 StorageAdapter 接口的存储对象
- 使用适配器的 getItem/setItem/removeItem 方法操作存储
- 提供与 useLocalStorage/useSessionStorage 相同的 API
- 支持自定义存储后端(如 IndexedDB、内存缓存等)
存储适配器可以是:
window.localStoragewindow.sessionStorage- 自定义实现(如内存存储、文件存储等)
通用的存储抽象,useLocalStorage 和 useSessionStorage 都基于此实现。