indexedDB使用方式之localForage
localForage是什么
localForage 是基于 indexedDB 封装的库,我们可以通过使用localForage,简化操作IndexedDB,方便使用。
优势
- 存储量大 ,百兆级,或者无限;
- 使用方便 ,无需序列化,异步方式;
- 兼容性好 ,默认使用IndexedDB,不支持会使用WebSQL或 localStorage;兼容性
使用方式
-
引入
import localforage from 'localforage'
-
多实例
var store = localforage.createInstance({ name: "nameHere" }); var otherStore = localforage.createInstance({ name: "otherName" }); // Setting the key on one of these doesn't affect the other. store.setItem("key1", {a:1}); otherStore.setItem("key2", "123123");
-
读取
store.getItem('key1').then(function (value) { // we got our value }).catch(function (err) { // we got an error }); // 或者 try { const value = await otherStore.getItem('key2'); // This code runs once the value has been loaded // from the offline store. console.log(value); } catch (err) { // This code runs if there were any errors. console.log(err); }
-
其他:删除就是我们熟知的:
removeItem
,清空:clear