vue 中使用 IndexedDB

封装 IndexedDB 

初始化数据库

    dbInit () {
      return new Promise((resolve, reject) => {
        const connection = window.indexedDB.open('dbname', 2)
        connection.onsuccess = function (event) {
          resolve(event.target.result)
        }
        connection.onupgradeneeded = function (event) {
          const db = event.target.result
          if (!db.objectStoreNames.contains('person')) {
            db.createObjectStore('person', { autoIncrement: true })
          }
        }
        connection.onerror = function (err) {
          reject(err)
        }
      })
    }

封装 新增, 读取, 读取所有 方法

    dbOperation (type, data) {
      let typeList = ['add', 'get', 'getAll']
      if (!typeList.includes(type)) {
        throw new Error(`操作类型错误, 仅支持: ${typeList.toString()} 方法`)
      }
      const readType = type === 'add' ? 'readwrite' : 'readonly'
      const res = await this.dbInit()
      const objectStore = res.transaction('person', readType).objectStore('person')
      const response = new Promise((resolve, reject) => {
        const request = objectStore[type](data)
        request.onsuccess = (res) => {
          resolve(res.target.result)
        }
        request.onerror = (err) => {
          reject(err)
        }
      })
      return response
    }

函数调用

    async add () {
      const data = {
        name: 'name',
        age: 'age',
        email: 'email@11.11'
      }
      const res = await this.dbOperation('add', data)
      console.log(res)
    },
    async read () {
      const res = await this.dbOperation('get', 1)
      console.log(res)
    },
    async readAll () {
      const res = await this.dbOperation('getAll')
      console.log(res)
    },
原文地址:https://www.cnblogs.com/W-it-H-ou-T/p/14140658.html