indexdbwrapper的简单使用(vue项目)

机缘巧合

由于我做的毕设需要在前端存储大量的点云数组,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

如果觉得有用请给我点个赞吧

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值