Appearance
storage
storage 提供了一个统一的本地存储管理方案,采用单例模式封装了 localStorage、sessionStorage 和 cookie 的操作方法。
初始化
在使用存储功能之前,建议先创建存储实例并设置统一的前缀:
typescript
import { Storage } from '@qxs-bns/utils'
// 使用自定义前缀创建实例
const storage = new Storage('myapp_')
// 不传参数则使用默认前缀 'qxs_'
const storage = new Storage()
基础用法
loading
高级用法
loading
API
获取存储实例
typescript
import { Storage } from '@qxs-bns/utils'
// 创建存储实例
const storage = new Storage('custom_prefix_')
// 使用默认前缀
const storage = new Storage()
local / session
方法 | 说明 | 参数 | 返回值 |
---|---|---|---|
has(key: string, usePrefix?: boolean) | 检查是否存在指定键 | key: 存储键名 usePrefix: 是否使用前缀(默认true) | boolean |
get(key: string, usePrefix?: boolean) | 获取存储值 | key: 存储键名 usePrefix: 是否使用前缀(默认true) | string | null |
set(key: string, value: string, usePrefix?: boolean) | 设置存储值 | key: 存储键名 value: 存储值 usePrefix: 是否使用前缀(默认true) | void |
remove(key: string, usePrefix?: boolean) | 删除指定键值对 | key: 存储键名 usePrefix: 是否使用前缀(默认true) | void |
clear() | 清空所有存储 | - | void |
cookie
方法 | 说明 | 参数 | 返回值 |
---|---|---|---|
has(key: string, usePrefix?: boolean) | 检查是否存在指定 cookie | key: cookie 名 usePrefix: 是否使用前缀(默认true) | boolean |
get(key: string, usePrefix?: boolean) | 获取 cookie 值 | key: cookie 名 usePrefix: 是否使用前缀(默认true) | string | null |
set(key: string, value: string, expires?: number, path?: string, domain?: string, usePrefix?: boolean) | 设置 cookie | key: cookie 名 value: cookie 值 expires: 过期天数(默认1天) path: 路径(默认'/') domain: 域名(默认当前顶级域名) usePrefix: 是否使用前缀(默认true) | void |
remove(key: string, path?: string, domain?: string, usePrefix?: boolean) | 删除指定 cookie | key: cookie 名 path: 路径(默认'/') domain: 域名(默认当前顶级域名) usePrefix: 是否使用前缀(默认true) | void |
clear() | 清空所有 cookie | - | void |
使用示例
基础用法
typescript
import { Storage } from '@qxs-bns/utils'
// 创建存储实例
const storage = new Storage('myapp_')
// localStorage 操作
storage.local.set('user', 'john')
const user = storage.local.get('user') // 'john'
storage.local.has('user') // true
storage.local.remove('user')
// sessionStorage 操作
storage.session.set('token', 'abc123')
const token = storage.session.get('token') // 'abc123'
storage.session.remove('token')
// cookie 操作
storage.cookie.set('theme', 'dark', 7) // 7天过期
const theme = storage.cookie.get('theme') // 'dark'
storage.cookie.remove('theme')
不使用前缀
typescript
const storage = new Storage()
// 不使用前缀存储
storage.local.set('global_key', 'value', false)
storage.local.get('global_key', false) // 'value'
Cookie 高级配置
typescript
const storage = new Storage()
// 设置 cookie 并指定过期时间、路径和域名
storage.cookie.set('session_id', 'abc123', 30, '/api', '.example.com')
// 删除指定路径和域名的 cookie
storage.cookie.remove('session_id', '/api', '.example.com')
注意事项
- 建议在应用初始化时创建存储实例并设置统一的前缀
- 所有存储的键名都会自动添加配置的前缀
- Cookie 操作会自动处理域名、编码解码等细节
- 每个存储实例都有独立的前缀配置
- 如果未传入前缀,将使用默认前缀 'qxs_'
usePrefix
参数允许你选择是否使用配置的前缀- Cookie 的
expires
参数以天为单位