sunqy 2019-12-27
数据库的打开/新增/删除
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); } }