- 创建数据库
onsuccess 成功回调
onerror 打开数据库失败回调
onupgradeneeded 创建储存空间(表), 创建索引。 keyPath 和 autoIncrement 使用参考文档。 触发条件: 数据库不存在或数据库版本号增大
添加计时器,防止执行添加数据或查询数据时,没有打开数据库成功onsuccess
let timeInter: any = null
let DB_NAME = 'indexedDB-test', VERSION = 1, db: any
let request = indexedDB.open(DB_NAME, VERSION)
request.onsuccess = function(event: any) {
db = event.target.result
// console.log(event.target === request); // true
db.onsuccess = function(event: any) {
// console.log('数据库操作成功!');
};
db.onerror = function(event: any) {
};
// console.log('打开数据库成功!');
};
request.onerror = function(event: any) {
console.error('创建数据库出错');
linkfail = true
clearInterval(timeInter)
timeInter = null
};
request.onupgradeneeded = function(event: any) {
let database = event.target.result
let objectStore = database.createObjectStore("wait", { keyPath: "id" });
// objectStore.createIndex('id', 'id', { unique: true });
// objectStore.createIndex('title', 'title', { unique: false })
}
- 添加数据
put 有更新作用,存在不会报错
Promise 包装,形成异步和 报错误不会卡页面
export const addData = (data: string) => {
allData = null
return new Promise((resolve, reject) => {
let transaction = db.transaction(['wait'], 'readwrite');
transaction.oncomplete = function(event: any) {
};
transaction.onerror = function(event: any) {
reject(event)
};
transaction.onabort = function(event: any) {
}
let objectStore = transaction.objectStore('wait')
let store = objectStore.put({
id: data,
});
store.onsuccess = function(event: any) {
// console.log('插入成功!');
resolve(event.target.result)
}
store.onerror = function(event: any) {
reject(event)
}
})
}
- 查询所有数据
查询所有使用 游标(参考文档),openCursor。有个计时器循环,直到数据库打开成功或失败。缓存查询所有数据,直到页面刷新和添加数据,才会查询
const queryAll = (resolve: any, reject: any) => {
if (allData) {
resolve(allData)
return
}
let transaction = db.transaction('wait');
transaction.oncomplete = function(event: any) {
};
transaction.onerror = function(event: any) {
reject(event)
};
transaction.onabort = function(event: any) {
}
let objectStore = transaction.objectStore('wait')
let store = objectStore.openCursor();
let wait_infos = new Map()
store.onsuccess = function(event: any) {
let cursor = event.target.result;
if (cursor) {
wait_infos.set(cursor.value.id, 1)
cursor.continue();
}
else {
allData = wait_infos
resolve(wait_infos)
}
}
store.onerror = function(event: any) {
console.log(event)
console.log('查询失败!');
reject(event)
}
}
let allData: any = null
export const getAllData = () => {
return new Promise((resolve, reject) => {
if (db) {
queryAll(resolve, reject)
} else {
timeInter = setInterval(() => {
if (db) {
queryAll(resolve, reject)
clearInterval(timeInter)
timeInter = null
}
if (linkfail) {
reject('数据库连接失败')
}
}, 1000)
}
})
}