<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IndexDB</title>
</head>
<body>
</body>
<script>
var db;
class DB {
db;
dataName;
config;
version
constructor(dataName, config = {}, version = 1) {
this.dataName = dataName;
this.config = config;
this.version = version;
console.log('new DB');
this.init();
}
init() {
return new Promise((resolve, reject) => {
const dataName = this.dataName;
const version = this.version;
const config = this.config;
const req = indexedDB.open(this.dataName, this.version);
req.onupgradeneeded = (event) => {
console.log('onupgradeneeded');
const db = event.target.result;
// 判断是否存在ObjectStore
if (!db.objectStoreNames.contains(dataName)) {
// 主键 autoIncrement 自增加
const store = config.keyPath && db.createObjectStore(dataName, { keyPath: config.keyPath, autoIncrement: !!config.autoIncrement });
// 索引 unique 唯一值
config.index && store.createIndex(config.index, config.indexKey, { unique: config.indexUnique });
}
}
req.onsuccess = (event) => {
console.log('onsuccess');
this.db = event.target.result;
resolve(this.db);
}
req.onerror = (error) => {
reject(error);
}
});
}
add(data) {
return new Promise(async (resolve, reject) => {
console.log(this.db);
if (!this.db) {
await this.init();
}
const db = this.db;
console.log(this.db);
// 这个时候就报错了
const transaction = db.transaction([this.dataName], 'readwrite');
const store = transaction.objectStore(this.dataName);
const handle = store.add(data);
handle.onsuccess = () => {
console.log('新增成功');
db.close();
resolve(true);
};
handle.onerror = (error) => {
console.log('新增失败', error);
db.close();
reject(error);
};
}).catch(error => reject(error));
}
}
const myDB = new DB('myDB');
setTimeout(() => {
myDB.add({ id: 1, name: 'name1' })
}, 300);
</script>
</html>
new 的时候忘记传参数了。自己把自己坑了,。。。。。。。。。。。。。。。