indexedDB 使用
Posted 美力
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了indexedDB 使用相关的知识,希望对你有一定的参考价值。
数据库的打开/新增/删除
initDB() { let _this = this; let obj = { id: 1, name: _this.addForm.content } let indexedDB = window.indexedDB || window.webkitindexedDB || window.msIndexedDB || mozIndexedDB; request = indexedDB.open(‘edp‘); //edp数据库名称 request.onsuccess = function(event) { console.log(‘打开成功‘); db = event.target.result; //清空表 let tx = db.transaction(‘messageCode‘, ‘readwrite‘); let store = tx.objectStore(‘messageCode‘); store.clear(); //添加表 let objStore; let transaction = db.transaction([‘messageCode‘], ‘readwrite‘); objStore = transaction.objectStore(‘messageCode‘); objStore.add(obj); } request.onupgradeneeded = function(event) { db = event.target.result; let store; //创建表 if(!db.objectStoreNames.contains(‘messageCode‘)) { store = db.createObjectStore(‘messageCode‘, { keyPath: ‘id‘, autoIncrement: true }); } console.log(‘创建对象仓库成功‘); } }
更改表
//内容更改 changeCode() { let obj = { id: 1, name: this.addForm.content } //更新表 let tx = db.transaction(‘messageCode‘, ‘readwrite‘); let store = tx.objectStore(‘messageCode‘); let req = store.get(1); req.onsuccess = function(e) { store.put(obj); console.log(‘更新成功‘); }; },
新页面获取表
created() { let _this = this; var request = window.indexedDB.open(‘edp‘); var db; request.onerror = function() { console.log(‘数据库打开报错‘); } request.onsuccess = function(event) { console.log(‘数据库打开成功‘); db = event.target.result; var transaction = db.transaction([‘messageCode‘], ‘readwrite‘); var objStore = transaction.objectStore(‘messageCode‘); // 读取数据 var req = objStore.get(1); req.onsuccess = function(e) { if(req.result) { console.log(‘已经查询到数据为:‘); console.log(req.result); _this.online = req.result.name; } else { console.log(‘未查询到数据‘); } } } request.onupgradeneeded = function(event) { console.log(‘数据库升级事件‘); db = event.target.result; console.log(db); } }
以上是关于indexedDB 使用的主要内容,如果未能解决你的问题,请参考以下文章
使用 dexie 和 angular 从 indexedDB 获取数据
vue+elementUi+IndexedDB完整代码浏览器本地存储缓存数据库openaddgetAllopenCursorputdeletewindowobjectStore