yux-storage
yux-storage 是一个基于 HTML5 IndexedDB 封装的 Web 本地数据离线存储库。
特点
- 使用类似 localStorage API, 无需考虑 IndexedDB 的复杂概念,上手无压力。
- 支持回调和 Promise 两种方式,各凭所愿。
- 非常轻量,100 行左右的源码,压缩后更小。
以下是继承 IndexedDB 的特点
- 可以存储多种类型的数据,而不仅仅是字符串。
- 储存空间大,一般来说不少于 250MB,甚至没有上限。
- 异步操作,在进行大量数据存取时不会阻塞应用程序。
快速开始
安装
- 直接在 github 获取 yux-storage.js
<script src="yux-storage.js"></script>
- 直接使用 unpkg 在线链接
<script src="https://unpkg.com/yux-storage"></script>
- 通过 npm 安装
npm i yux-storage
使用
通过 script 引用,会得到一个全局变量 yuxStorage
通过 npm 安装,需要 import 导入
import yuxStorage from 'yux-storage';
在页面中使用
yuxStorage.getItem('key',function(err,value){
if (err) {
console.log('出错了')
}
})
yuxStorage.setItem('key').then(doSomethingElse)
const value = await yuxStorage.getItem('key')
console.log(value)
API
获取或设置离线仓库中的数据的 API。风格参考 localStorage API
GETITEM
yuxStorage.getItem(key, callback)
从仓库中获取 key 对应的值并将结果提供给回调函数。如果 key
不存在,getItem()
将返回 null
。
所有回调函数的第一个参数为错误标识,如果为 true
,说明出错
示例
yuxStorage.getItem('somekey').then(function(value) {
console.log(value);
})
const value = await yuxStorage.getItem('somekey');
console.log(value);
yuxStorage.getItem('somekey', function(err,value) {
console.log(value);
});
SETITEM
yuxStorage.setItem(key, value, callback)
将数据保存到离线仓库。你可以存储如下类型的 JavaScript 对象:
- Array
- ArrayBuffer
- Blob
- Float32Array
- Float64Array
- Int8Array
- Int16Array
- Int32Array
- Number
- Object
- Uint8Array
- Uint8ClampedArray
- Uint16Array
- Uint32Array
- String
可能不太完整,理论上支持任意格式的数据
示例
yuxStorage.setItem('somekey', 'some value').then(function (value) {
console.log(value);
})
yuxStorage.setItem('my array', [1, 2, 'three']).then(function(value) {
console.log(value[0]);
})
yuxStorage.setItem([1,2,3], [1, 2, 'three'])
const file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
yuxStorage.setItem('file', file)
REMOVEITEM
yuxStorage.removeItem(key, callback)
从离线仓库中删除 key 对应的值。
示例
yuxStorage.removeItem('somekey').then(function() {
console.log('Key is cleared!');
})
CLEAR
yuxStorage.clear(callback)
从数据库中删除所有的 key,重置数据库。
其实就是遍历,然后执行 REMOVEITEM
示例
yuxStorage.clear().then(function() {
console.log('Database is now empty.');
})
KEY
yuxStorage.key(keyIndex, callback)
根据 key 的索引获取其名
有些鸡肋的方法,很多时候我们不知道键的索引。
yuxStorage.key(2).then(function(keyName) {
console.log(keyName);
})
KEYS
yuxStorage.keys(callback)
获取数据仓库中所有的 key。
localStorage API 并没有这个方法,但比上面的 key 要有用的多。
兼容性
不支持 IE
兼容性取决于 indexedDB 和 Promise
联系我
有相关问题或者意见可与我联系 yanwenbin@yuewen.com