indexdb.js封装使用

1,封装

// indexedDB.js,浏览器本地数据库操作
import API from '@/api/api_database'
let indexdb = {
  // indexedDB兼容
  indexedDB: window.indexedDB || window.webkitindexedDB || window.msIndexedDB || mozIndexedDB,
  db: '',
  // initDB
  initDB () {
    let request = indexedDB.open('myDB')
    // err
    request.onerror = event => {
      console.log('数据库打开/创建报错', event)
    }
    // 如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件upgradeneeded。
    // 升级后自动触发success
    request.onupgradeneeded = event => {
      let db = event.target.result// 数据库对象
      this.db = db
      // 建表 名为errorDatas,主键为task_id
      console.log(19, this)
      const store = this.db.createObjectStore('errorDatas', {
        // keyPath: 'id'
        keyPath: 'task_id'
      })
      // 新建索引名称、索引所在的属性、配置对象(说明该属性是否允许有重复的值)
      store.createIndex('task_id', 'task_id', {
        unique: true
      })
      store.createIndex('file', 'file', {
        unique: false
      })
      console.log('数据库升级')
    }
    // success
    request.onsuccess = event => {
      this.db = event.target.result
      console.log(36, this)
      console.log('数据库打开/创建成功', event)
      this.getList()
    }
  },
  add (errorData, taskIds) {
    console.log(JSON.stringify(errorData))
    // 建立读写事务,向对象仓库写入数据记录
    console.log(43, this)
    let request = this.db.transaction(['errorDatas'], 'readwrite').objectStore('errorDatas').add({
      id: new Date().getTime(),
      file: errorData,
      task_id: taskIds
    })
    request.onsuccess = event => {
      this.errorDatas = {}
      // 获取数据列表
      this.getList()
    }
    request.onerror = event => {
    }
  },
  read (id, resarchId, scoketData) {
    var transaction = this.db.transaction(['errorDatas'])
    let objectStore = transaction.objectStore('errorDatas')
    console.log(333, objectStore)
    // let request = objectStore.getAll(objectStore.id)
    let request = objectStore.get(id)
    console.log(338, request)
    request.onerror = function (event) {
      console.log('获取列表失败')
    }
    let _this = this
    request.onsuccess = function (event) {
      if (request.result) {
        console.log('file: ', request.result)
        let fileList = request.result.file
        console.log('348', fileList)
        console.log(resarchId)
        let arrs = []
        for (let i = 0; i < fileList.length; i++) {
          var formData = new FormData()
          console.log('352', fileList[i])
          formData.append('file', fileList[i].file.raw)
          formData.append('research_group_id', resarchId)
          arrs.push(formData)
        }
        console.log('356', id)
        for (var i = 0; i < arrs.length; i++) {
          console.log('哟哟切克闹' + i)
          API.sendUploadData(id, arrs[i]).then((res) => {
            if (res.code === 10000) {
              if (scoketData.scoket) {
                let scoketDatas = scoketData.scoket
                let success = JSON.parse(scoketDatas).data.transfer_success
                let totals = JSON.parse(scoketDatas).data.total
                if (success === totals) {
                  _this.clickDel(id)
                }
              }
            } else if (res.code === 10001) {
            }
          })
        }
      } else {
        console.log('未获得数据记录')
      }
    }
  },
  getList () {
    var transaction = this.db.transaction(['errorDatas'])
    let objectStore = transaction.objectStore('errorDatas')
    let list = []
    // 遍历数据库
    objectStore.openCursor().onsuccess = event => {
      let cursor = event.target.result
      if (cursor) {
        list.push(cursor.value)
        cursor.continue()
      } else {
        this.list = list
      }
    }
  },
  update () {
    let request = this.db.transaction(['errorDatas'], 'readwrite').objectStore('person').put({
      file: '李四'
    })
    request.onsuccess = event => {
      console.log('数据更新成功')
    }
    request.onerror = event => {
      console.log('数据更新失败')
    }
  },
  clickDel (id) {
    var request = this.db.transaction(['errorDatas'], 'readwrite')
      .objectStore('errorDatas')
      .delete(id)
    request.onsuccess = event => {
      this.getList()
    }
    request.onerror = event => {
    }
  }
}
export default {
  indexdb
}

2,mian.js引入

import indexdb from './api/indexDB'
Vue.prototype.$indexDB = indexdb

3,在需要使用的地方调用方法


  this.$indexDB.indexdb.initDB() // 创建数据库  
  this.$indexDB.indexdb.read(row.id, resarchId, this.scoketData)

 

posted @ 2022-03-29 19:04  武向前  阅读(993)  评论(0编辑  收藏  举报