初探indexDB

770 阅读1分钟

背景:

浏览器储存是一个老生常谈的问题,在此之前就有很多储存方式,但是为什么又提出indeDB新的储存方式呢,其实个人感觉主要是下面两个原因

  • 1 大小限制 以前的cookie, localStorage 对大小有一定的限制
  • 2 丰富查询能力, 是基于面向对象的,不需要结构化查询语言

基本概念

操作流程

1 打开数据库。
this.DBOpenRequest = window.indexedDB.open(name, version)

2 在数据库中创建一个对象仓库(第一次创建时会触发onupgradeneeded 事件)

const objectStore = db.createObjectStore('info', { keyPath: 'id', autoIncrement: true });
objectStore.createIndex('id', 'id', { unique: true });
objectStore.createIndex('name', 'name');

3 启动一个事务,通过事务进行一些列增删改查

const transaction = this.db.transaction(this.db.objectStoreNames, "readwrite");
objectStore = transaction.objectStore('info');

// 增加数据到数据库
objectStore.add(item)

// 查找
const request = this.objectStore.openCursor();
return new Promise((resolve, reject) => {
            request.onsuccess = evt => {
                const cursor = evt.target.result
    
                if (cursor) {
                    list.push(cursor.value);
                    cursor.continue();
                } else {
                    resolve(list);
                }
            }

            request.onerror = reject;
        })
// 删除
objectStore.delete(id)
// 更新
objectStore.put({ id, ... })

一个小demo