Vue使用 IndexDB vue操作IndexDB数据库 Vue操作IndexDB数据库

Vue使用 IndexDB vue操作IndexDB数据库 Vue操作IndexDB数据库

大部分场景使用 LocalStore都足够了,但是 如果要考虑大数据的话,LocalStore支持并不是很好,有内存限制,并且数据过大 LocalStore解析和存储性能不是很好,这时候可以使用 IndexDB,数据格式 是和 数据库一样,可以创建多个数据库,数据库里面有多个表

安装 IndexDB类库

原生 IndexDB操作API并不是很方便,可以使用第三方类库,可以极大的减少工作量,调用IndexDB和LocalStore API很像,我这边使用过的是 LOCALFORAGE 官网

支持存储类型有:
在这里插入图片描述

npm

npm install localforage

或者 使用 yrm

yarn add localforage

引入 localForage

main.js 中引用

import Vue from 'vue'
import App from './App'
import router from './router'

// IndexDB封装类库 https://localforage.github.io/localForage/#installation
import localforage from 'localforage'

Vue.use(localforage)

// 将 localforage 挂载到全局示例, 这样就可以在任何地方 用 this.$localforage 操作
Vue.prototype.$localforage = localforage

console.info('localforage初始化成功,使用 this.$localforage 调用')

// 创建一个 默认的 IndexDB数据库挂载到全局
const demoDataBase = localforage.createInstance({
  name: 'demoDataBase'
})

Vue.prototype.$demoDataBase  = demoDataBase 
console.info('默认数据库 demoDataBase  初始化成功,使用 this.$demoDataBase 调用')

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

测试 新增数据、获取数据

在 demoDataBase数据库新增一条数据

    // 操作 demoDataBase数据库
    this.$demoDataBase.setItem('测试demoDataBase', '我是测试值').then(function (value) {
    // Do other things once the value has been saved.
      console.log(value)
    }).catch(function (err) {
    // This code runs if there were any errors
      console.log(err)
    })

	// 不需要回调
	this.$demoDataBase.setItem('测试demoDataBase2', '我是测试值2')

查看是否生效,数据已经新增上去了,一共两条

在这里插入图片描述

获取数据也很简单

    // 操作 demoDataBase数据库
    this.$demoDataBase.getItem('测试demoDataBase').then(function (value) {
    // Do other things once the value has been saved.
      console.log(value)
    }).catch(function (err) {
    // This code runs if there were any errors
      console.log(err)
    })

    // 不需要回调
    this.$demoDataBase.getItem('测试demoDataBase2')

还有删除、查询等更多API不一一演示了,可以进入官网 查看更多

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值