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不一一演示了,可以进入官网 查看更多

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐