参考
- 浏览器数据库 IndexedDB 入门教程 - 阮一峰的网络日志(基本概念)
- 使用 IndexedDB - Web API 接口参考 | MDN (主要参考)
- IDBDatabase - Web API 接口参考 | MDN
- IDBObjectStore - Web API 接口参考 | MDN
HTML5 indexedDB前端本地存储数据库实例教程 « 张鑫旭-鑫空间-鑫生活
第一个例子
session-db.js
实现 miscStorage(仿 sessionStorage)
- 无需序列化反序列化
- 能存储含环对象
- 深拷贝
const sessionDB = {
db: null,
dbname: 'sessionDB',
load() {
return new Promise((resolve, reject) => {
let sessionDBLoaded = sessionStorage.getItem('sessionDBLoaded');
if (!sessionDBLoaded) {
let request = indexedDB.deleteDatabase(this.dbname);
request.onerror = event => {
console.error(event);
return reject(event);
};
request.onsuccess = event => {
console.log('清除了原 sessionDB');
};
}
let openRequest = indexedDB.open(this.dbname, 1);
openRequest.onerror = (event) => {
return reject(event);
};
// db 创建或版本变更时的事件处理,十分重要。
// 原本没有库,或者 version 更改后会触发 onupgradeneeded
// onupgradeneeded 中写的是表结构的改变,类似于关系型数据库的 DDL
// IDBDatabase.deleteObjectStore 与 IDBDatabase.createObjectStore 一样,此方法只能在 onupgradeneeded 中调用
openRequest.onupgradeneeded = (event) => {
this.db = event.target.result;
if (!this.db.objectStoreNames.contains('misc')) {
objectStore = this.db.createObjectStore("misc", {
keyPath: "key" });
objectStore.createIndex("key", "key", {
unique: true });
}
console.log('更新了 sessionDB');
};
openRequest.onsuccess = (event) => {
this.db = event.target.result;
if (sessionDBLoaded) {
console.log('加载了原 sessionDB');
}
sessionStorage.setItem('sessionDBLoaded', true);
return resolve(this.db);
};
});
},
destroy() {
return new Promise((resolve, reject) => {
if (!this.db) {
console.log('db is null');
return resolve();
}
this.db.close();
let request = indexedDB.deleteDatabase(this.dbname);
request.onerror = event => {
console.error(event);
return reject(event);
};
request.onsuccess = event => {
sessionStorage.removeItem('sessionDBLoaded');
console.log('销毁了 sessionDB');
return resolve();
};
});
}
}
sessionDB.load();
const miscStorage = {
getObjectSotrage() {
return sessionDB.db.transaction(["misc"], "readwrite").objectStore("misc");
}