码迷,mamicode.com
首页 > 数据库 > 详细

indexedDB 使用

时间:2019-12-27 13:08:53      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:onupgrade   升级   hang   index   request   dwr   names   web   nbsp   

数据库的打开/新增/删除

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 使用

标签:onupgrade   升级   hang   index   request   dwr   names   web   nbsp   

原文地址:https://www.cnblogs.com/zhaozhenzhen/p/12106539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!