1. 前言
最近刚入职在看新项目的代码,学习了很多新的代码封装思路和模块化的思想。而且也了解到了IndexedDB数据库的使用方法,开一篇文章来总结下IndexedDB在项目中的使用。
2. IndexedDB
2-1. IndexedDB是什么
通俗地说,IndexedDB
就是浏览器提供的本地数据库,它可以被网页脚本创建和操作。
2-2. 为什么要使用它
以往做网页存储,我们一般使用cookie
和localStorage
或者sessionStorage
。但是这两种方法一个存储的空间有限,一个也只能建立很简单的对象设置和获取属性。而IndexedDB
不仅能存储大量数据,而且还能建立索引和提供查找接口。在大型项目中会有很大的优势。
关于
IndexedDB
的特点和基本概念阮老师的博客写的很清楚。我这里不做概述。本篇文章只是为了记录下我现在的项目中是如何使用IndexedDB
,介绍基本的使用方法。浏览器数据库
3. 使用方法
3-1. 打开或者新建数据库
// 获取indexedDB数据对象
const indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB
// 打开或者新建数据库
/**
* @param {string} databaseName: 打开/新建的数据库名称
* @param {string} version: 数据库版本号
*/
let dbRequest = window.indexedDB.open(databaseName, version);
3-2. 设置不同的处理方法
打开数据库后我们能拿到一个IndexDBRequest
对象,这个对象有三个处理事件的方法,来处理打开或者新增数据库的操作结果
- success事件
dbRequest.onsuccess = event => {
console.log("数据库打开成功");
// 数据库的实例对象
const db = event.target.result;
}
- error事件
dbRequest.onerror = event => {
console.log("数据库打开失败");
}
- upgradeneeded事件
- 对于打开数据库来说如果指定的版本大于数据库的实际版本就会这个数据库升级事件,一般来说不会处理这个
// 打开已有数据库如果指定的version高于当前数据的version
window.indexedDB.open(databaseName, version);
dbRequest.onupgradeneeded = event => {
console.log("数据库需要升级");
}
- 对于新建数据库,没有版本,新建的时候就会直接触发这个事件,通常我们会在这个事件中区新增数据库表和索引。
dbRequest.onupgradeneeded = event => {
// 通过事件对象的`target.result`创建新的数据库表
const db = event.target.result;
// 创建前先判断该数据库表是否存在
if (!db.objectStoreNames.contains("test")) {
// 创建名为`test`的数据库表并指定主键为`id`
let objectStore = db.createObjectStore("test", { keyPath: "id" });
// 如果数据记录里面没有合适作为主键的属性,那么可以让 IndexedDB 自动生成主键。
// let objectStore = db.createObjectStore("test", { autoIncrement: true });
// 创建索引
/**
* @param {string} 索引名称
* @param {string} 索引所在的属性
* @param {object} 配置对象: 说明该属性是否包含重复的值
*/
objectStore.createIndex("id", "id", { unique: true });
objectStore.createIndex("value", "value", { unique: true });
}
};
3-3. 操作数据
操作数据分为新增
,读取
,更新
,删除
等。这些操作都需要通过事务完成。
// 打开数据库开始操作数据
dbRequset.onsuccess = event => {
// 新建事务
// 新建时必须指定表格名称和操作模式("只读"或"读写")
const trans = db.transaction(["test"], "readwrite");
// 拿到IDBObjectStore对象
const dictStore = trans.objectStore("test");
// 通过IDBObjectStore对象操作数据
// 读取数据
const getResp = disStore.get("1");
// 新增数据
const addResp = disStore.add({ id: 1, value: "test"});
// 更新数据
const putResp = disStore.put({ id: 1, value: "test1"});
// 删除数据
const deleteResp = disStore.delete(1);
// 上述几种操作数据库的方法都会返回一个连接对象
// 通过监听返回的连接对象来判断是否操作成功
getResp.onerror = function(event) {
console.log('事务失败');
};
getResp.onsuccess = function( event) {
if (request.result) {
console.log('value: ' + request.result.value);
} else {
console.log('未获得数据记录');
}
};
}
3-4. 使用索引
我们在上面对value
字段建立了索引
objectStore.createIndex("value", "value", { unique: true });
所以我们可以通过索引value
去查找数据了
// 也要先创建事务指定为只读
const trans = db.transaction(["test"], "readonly");
// 拿到IDBObjectStore对象
const dictStore = trans.objectStore("test");
// 拿到连接对象
let request = dictStore.index("value").get("test");
request.onsuccess = function(event) {
if (event.target.result) {
console.log(event.target.result);
} else {
console.log('未获得数据记录');
}
};
最近项目中用到了很多新技术,微前端,发布组件,浏览器数据库等等,我目前也在一边学习一边总结。如果这篇文章对大家有帮助的话点个赞呗❤️❤️