Better localStorage, subscribable localStorage, expirable localStorage
!Build Status

!license
!release
English | 简体中文
🦄本地存储localStorage的封装,提供过期时间设置和订阅功能,提供简单API使用,没有依赖,压缩只有 3.81KB(gzipped: 1.39KB)。
- 比较好的localStorage, 也认为是下一代的localStorage
- 易学易用
- 支持数据的过期时间
- 支持数据变化的监听
- 使用 TypeScript 构建,提供完整的类型定义文件
``bashnpm 安装
npm install storetify
#pnpm 安装
pnpm add storetify
`
`bash`
npm run build
`bash`
npm test
`js`
import store from 'storetify';
store("test","storetify");
或者在您的HTML中手动下载并引入 storetify.min.js,你也可以通过 UNPKG 进行下载:
`html`
存储数据
store.set(key, data[, expires]);store(key, data[, expires]);
效果相同
`js`
store.set("test","1"); //⇒1
store.set("test","1",3); //⇒1 3秒后test过期
获取key的字符串数据
store.get(key)store(key)
效果相同
`js`
store.get("test"); // 获取test的字符串数据
store("test"); // 功能同上
`ts
store.get<自定义类型>("test"); // 获取test的字符串数据
// 或者
const t:自定义类型 = store.get("test");
store("test"); // 功能同上
// 或者
const t:自定义类型 = store.("test");
`
删除key下的数据 store.remove(key)
`js`
store.remove("test");
清空所有 key/data store.clear()
`js`
store.clear(); // 会发布所有key值的变化
判断是否存在并返回 true/false store.has(key)
`js`
store.has("test"); //⇒true
订阅test的数据变化
`js`
store.subscribe("test",(e)=>{})
对于事件变量e,是一个来自StorageEvent对象的简略对象,提供了一些实用的属性,可以很好的观察键值对的变化,如下表:
`ts
// JSON SAFE
export type JSONPrimitive = string | number | boolean | null
// eslint-disable-next-line no-use-before-define
export type StoretifyValue = JSONPrimitive | JSONObject | JSONArray
export interface JSONObject {
[key: string]: StoretifyValue
}
// eslint-disable-next-line no-use-before-define
export type JSONArray = Array
export type StoretifyEventValue = StoretifyValue
`
| Property | Type | Description|
| -------- | ------ | ------------------------------------------------------------ |
| key| string | 存储值的键,根据其修改、删除|StoretifyEventValue
| oldValue | | 上一次的值 |StoretifyEventValue
| newValue | | 当前新的值 |string
| type| | 事件类型 |StorageEvent
| native | | 原生事件 |
取消订阅test的数据变化
`js`
const someName = (e)=>{}
store.subscribe("test",someName)
store.unsubscribe("test",someName) // ⚠️注意,取消订阅不能是匿名方法
store.unsubscribe("test") // ⚠️注意,会取消test的所有订阅包括匿名函数
获取store的存储用量
`ts0.111 KB
store.getUsed() // 返回 `
来源:localStorage
| 特性 | Chrome | Firefox (Gecko) | Internet Explorer | Opera| Safari (WebKit) | iPhone(IOS) | Android | Opera Mobile | Window Phone |
| ------------ | ------ | --------------- | ----------------- | ------ | --------------- | ----------- | ------- | ------------ | ------------ |
| localStorage | 4+ | 3.5+| 8+| 10.50+ | 4+| 3.2+| 2.1+| 11+| 8+ |
JSON.stringify(localStorage).length` 当前占用多大容量