机缘巧合
由于我做的毕设需要在前端存储大量的点云数组,sessionStorage 满足不了我的需求,经我查询这种情况需要使用indexedDB数据库,读了别人的博客得知有 indexdbwrapper 这个包,所以决定使用这个方便的包。
代码
初始化 indexedDB 数据库连接,如果没有 t1 表则创建 t1 表
import IndexDBWrapper from 'indexdbwrapper'
export default {
name: 'Index‘,
data() {
return {
db: null
}
},
mounted() {
// 创建indexDB
if (this.db == null) {
const db = new IndexDBWrapper('db', 1, {
onupgradeneeded(e) {
const innerDb = e.target.result
console.log('index innerDb', innerDb)
// 如果不存在t1表则创建
console.log('t1表不存在', !innerDb.objectStoreNames.contains('t1'))
if (!innerDb.objectStoreNames.contains('t1')) {
// 创建表
innerDb.createObjectStore('t1', {
autoIncrement: false, // 自增
keyPath: 'id' // 主键
})
}
}
})
this.db = db
console.log('index db link', this.db)
}
}
}
onupgradeneeded 这个方法在 open() 数据库时会执行,你可以观察下 this.db 里面的属性
添加行到 t1 表中
let addObj = {
id: 0,
name: 'conference.txt',
points: [[...],[...]...] // 点云
}
let that = this
if (that.db != null){
// 打开数据库
that.db.open()
that.db.add('t1', addObj)
.then(res => {
console.log('add res res', res)
that.db.close() // 关闭数据库
console.log('add db after close', that.db)
})
.catch(err => {
console.log('add res err', err)
that.db.close() // 关闭数据库
console.log('add db after close', that.db)
})
}
根据主键查找 t1 表
let that = this
let id = 0
if (that.db != null) {
that.db.open()
console.log('open db before getKey', that.db)
that.db.get('t1', id)
.then(res => {
console.log('get res', res)
that.db.close()
}
.catch(err => {
console.log('get err', err)
that.db.close()
})
}
根据主键删除行
let that = this
let id = 0
if (that.db != null) {
console.log('before delete current db', that.db)
that.db.open()
that.db.delete('t1', id)
.then(res => {
console.log('delete res', res)
that.db.close()
})
.catch(err => {
console.log('delete err', err)
that.db.close()
})
}
清空 t1 表中数据
let that = this
if (that.db != null) {
that.db.open()
that.db.clear('t1')
.then(res => {
console.log('clear res', res)
that.db.close()
})
.catch(err => {
console.log('clear err', err)
that.db.close()
})
}
其他 indexedDB 数据库表操作请参考 超方便的 IndexDB 库
包地址 indexdbwrapper
如果觉得有用请给我点个赞吧