1.使用前端indexdb储存后台的数据
let db
// 打开本地数据库
export function openDb(DB_NAME, DB_VERSION, DB_STORE_NAME) {
console.log('打开本地数据库 ...')
var req = indexedDB.open(DB_NAME, DB_VERSION)
req.onsuccess = function(evt) {
console.log('打开本地数据库:', evt)
db = this.result
}
req.onerror = function(evt) {
console.log('打开本地数据库失败:', evt.target.errorCode)
}
// 创建indexdb时触发
req.onupgradeneeded = function(evt) {
console.log('创建indexdb', evt)
var result = evt.target.result
// 判断该对象空间时创建该对象空间
if (!result.objectStoreNames.contains(DB_STORE_NAME)) {
// 建立一个对象仓库来存储信息, trace 作为键路径(key path)
var objectStore = result.createObjectStore(DB_STORE_NAME, { keyPath: 'date' })
// 建立一个索引来通过处理厂数据来搜索。处理厂数据不会重复,所以我们使用 unique 索引
// objectStore.createIndex('plantData', 'plantData', { unique: true })
}
}
}
/**
* @param {string} store_name
* @param {string} mode either "readonly" or "readwrite"
*/
export function getObjectStore(storename, mode) {
var tx = db.transaction(storename, mode)
return tx.objectStore(storename)
}
// 添加信息
export function addPublication(storename, data) {
var store = getObjectStore(storename, 'readwrite')
console.log('添加信息', data)
data.map(v => {
var req
req = store.add(v)
req.onsuccess = function(evt) {
console.log('添加成功')
}
req.onerror = function() {
console.log('添加失败', this.error)
}
})
}
// 修改信息
export function putPublication(storename, data) {
var store = getObjectStore(storename, 'readwrite')
console.log('修改信息', data)
data.map(v => {
var req
req = store.put(v)
req.onsuccess = function(evt) {
console.log('修改成功')
}
req.onerror = function() {
console.log('修改失败', this.error)
}
})
}
// 删除某一条记录
export function deleteData(storename, key) {
const store = getObjectStore(storename, 'readwrite')
store.delete(key)
console.log('已删除存储空间' + storename + '中' + key + '记录')
}
// 根据存储空间