新项目中突然要前端存30M的文件作为数据,前端做业务驱动, sessionStorage、localStorage都无法存储这么大的数据,只好转用indexedDB,只记录一下最基础的使用。废话不说,直接上代码:
1、使用了 idb
这个库,它提供了简化的 IndexedDB 操作,安装:
npm install idb
2、本地引用
import { openDB } from 'idb';// 导入idb库
3、使用场景:初始化请求数据存入indexedDB,后续每次请求覆盖indexedDB中的数据
import { openDB } from 'idb';// 导入idb库
let db;
// 前端缓存所有数据
export function getAllPointList() {
return new Promise(function(resolve){
//请求后端获取的数据,allList
allList = testData
var scxy = store.state.basicData.DataDictionary.sendDriver//上传协议字典
var cjxy = store.state.basicData.DataDictionary.collectDriver//采集协议字典
var AllScPointList = allList.filter(i=> scxy.some(j=>i.DriverName == j.DataValue))//过滤上传协议点表
var AllCjPointList = allList.filter(i=> cjxy.some(j=>i.DriverName == j.DataValue))//过滤采集协议点表
// 数据库操作
// 打开IndexedDB数据库,如果不存在则创建
db = await openDB('webDB', 1, {
upgrade(db) {
// 创建'AllPointList'存储库
if (!db.objectStoreNames.contains('AllPointList')) {
db.createObjectStore('AllPointList', { keyPath: 'Id' });
}
// 创建'AllScPointList'存储库
if (!db.objectStoreNames.contains('AllScPointList')) {
db.createObjectStore('AllScPointList', { keyPath: 'Id' });
}
// 创建'AllCjPointList'存储库
if (!db.objectStoreNames.contains('AllCjPointList')) {
db.createObjectStore('AllCjPointList', { keyPath: 'Id' });
}
},
// 获取新数据并替换存储库中的数据
const transaction = db.transaction(['AllPointList', 'AllScPointList', 'AllCjPointList'], 'readwrite');
const pointListStore = transaction.objectStore('AllPointList');
const scPointListStore = transaction.objectStore('AllScPointList');
const cjPointListStore = transaction.objectStore('AllCjPointList');
// 清空存储库
await pointListStore.clear();
await scPointListStore.clear();
await cjPointListStore.clear();
// 将新数据存储到存储库中
allList.forEach((item) => pointListStore.put(item));
AllScPointList.forEach((item) => scPointListStore.put(item));
AllCjPointList.forEach((item) => cjPointListStore.put(item));
await transaction.complete;
var response = {
code:'success',
data:'成功'
}
resolve(response)
});
}
/**
* 读取数据db数据
* @param {object} db 数据库实例
* @param {string} storeName 仓库名称
* @param {string} key 主键值
*/
export function getDbData(storeName, key) {
return new Promise(async(resolve, reject) => {
db = await openDB('webDB', 1, {
upgrade(db) {},
});
const transaction = db.transaction([storeName], 'readwrite');
const pointListStore = transaction.objectStore(storeName);
const allPointList = await pointListStore.getAll();
resolve(allPointList);
});
}
4、页面中获取数据库值:
this.getDbData('AllScPointList').then(response=>{
console.log(response)
})