封裝 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) },