项目中用到了indexDB,做个笔记
const defaultOption = {
name: 'test',
version: 1,
storeName: 'today'
}
function IndexedDB(option) {
const indexdb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB
if (!indexdb) {
console.warn('indexdb does not support in this browser!')
return
}
this.indexedDB = indexdb
this._init(option)
}
IndexedDB.prototype._init = function(option) {
option = option || defaultOption
this.dbName = option.name
this.dbVersion = option.version
this.storeName = option.storeName
this.db = null
}
IndexedDB.prototype.open = function() {
const request = this.indexedDB.open(this.dbName, this.dbVersion)
const vm = this
request.onerror = function(e) {
console.log(e.currentTarget.error.message)
}
request.onsuccess = function(e) {
vm.db = e.target.result
}
request.onupgradeneeded = function(e) {
const db = e.target.result
if (!db.objectStoreNames.contains(vm.storeName)) {
// 创建object store
const store = db.createObjectStore(vm.storeName, {
keyPath: 'name'
})
// 创建索引
// store.createIndex('indexname', 'attr', {
// unique: false
// })
vm.db = db
}
}
}
function getStore(vm) {
// 事物只有一次,每次需要重新获得事务
const transaction = vm.db.transaction(vm.storeName, 'readwrite')
const store = transaction.objectStore(vm.storeName)
return store
}
function getStoreReadOnly(vm) {
// 事物只有一次,每次需要重新获得事务
const transaction = vm.db.transaction(vm.storeName)
const store = transaction.objectStore(vm.storeName)
return store
}
IndexedDB.prototype.addData = function(data) {
getStore(this).add(data)
}
IndexedDB.prototype.deleteDataByKey = function(key) {
getStore(this).delete(key)
}
IndexedDB.prototype.updateData = function(data) {
const request = getStore(this).put(data)
request.onsuccess = (e) => {
console.log('成功')
}
}
IndexedDB.prototype.getDataByIndex = function(indexes) {
const index = getStoreReadOnly(this).index(indexes.index)
const request = index.openCursor(IDBKeyRange.only(indexes.value))
request.onsuccess = (e) => {
const cursor = e.target.result
if (cursor) {
const res = cursor.value
console.log(res)
cursor.continue()
} else {
console.log('没有了')
}
}
}
//TODO 这个方法是不是可以更简单点
IndexedDB.prototype.getDataByKey = function(key) {
const request = getStoreReadOnly(this).get(key)
request.onsuccess = (e) => {
const res = e.target.result
if (!res) {
console.log('没有匹配的数据')
} else {
console.log(res)
}
}
}
IndexedDB.prototype.clearObjectStore = function() {
getStore(this).clear()
}
IndexedDB.prototype.closeDB = function() {
this.db.close()
}
IndexedDB.prototype.deleteDB = function() {
this.indexedDB.deleteDatabase(this.name)
}
export default IndexedDB
//TODO 需要返回值的怎么进行包装
// 用久了vue 连this 的作用域都没想到,耽误了好长时间。。。
本文介绍了一个基于IndexDB的JavaScript类库实现,用于在浏览器环境中进行数据存储操作。包括数据库的打开、升级、读写及数据的增删改查等功能。
646

被折叠的 条评论
为什么被折叠?



