初探indexDB

背景:

浏览器储存是一个老生常谈的问题,在此之前就有很多储存方式,但是为什么又提出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

转载于:https://juejin.im/post/5bee1be1e51d45710c6a5056

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值