一、先简单了解下什么是IndexedDB?
IndexedDB是一种底层API,用于客户端存储大量结构化数据,并提供了索引、事务、查询和游标等数据库特性。与localStorage和sessionStorage不同,IndexedDB是一个真正的数据库,它允许我们在用户的浏览器中存储几乎无限制的数据量,并通过复杂的查询来访问这些数据。
常用方法介绍:
1. open()
功能:打开或创建一个数据库。
参数:
- name:数据库的名称(字符串)。
- version:数据库的版本号(整数)。如果省略,打开已有数据库时默认为当前版本;新建数据库时默认为1。
返回值:返回一个IDBOpenDBRequest对象,用于处理打开数据库的结果。
事件:onsuccess、onerror、onupgradeneeded。
2、createObjectStore()
功能:在数据库的版本升级事件中创建新的对象仓库(Object Store)。
参数:
- name:对象仓库的名称(字符串)。
- options:一个对象,包含对象仓库的配置选项,如keyPath(主键路径)和autoIncrement(是否自动生成主键)。
返回值:无。
3、createIndex()
功能:在对象仓库中创建索引。
参数:
- indexName:索引的名称(字符串)。
- keyPath:索引基于的键路径(字符串或数组)。
- options:一个对象,包含索引的配置选项,如unique(是否唯一)。
返回值:无。
4、transaction()
功能:开始一个事务,用于执行对数据库的读写操作。
参数:
- storeNames:一个包含对象仓库名称的数组或单个对象仓库名称,指定事务将访问哪些对象仓库。
- mode:事务的模式(字符串),如readonly(只读)、readwrite(读写)。
返回值:返回一个IDBTransaction对象,用于管理事务。
5、objectStore()
功能:通过事务对象获取指定的对象仓库。
参数:对象仓库的名称(字符串)。
返回值:返回一个IDBObjectStore对象,用于对对象仓库进行操作。
add() 、put() 、delete() 、get() 、clear()
这些方法都是在IDBObjectStore对象上调用的,用于向对象仓库中添加、更新、删除、获取和清空数据。
具体可查看https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API
二、示例
<template><div><el-button @click="onOperation('add')" type="primary">增</el-button><el-button @click="onOperation('delete')" type="primary">删</el-button><el-button @click="onOperation('update')" type="primary">改</el-button><el-button @click="onOperation('query')" type="primary">查by主键</el-button><el-button @click="onOperation('queryIndex')" type="primary">查by索引</el-button><el-row><el-col :span="8"><div>书名:<el-input v-model="formData.title" /></div><div>作者:<el-input v-model="formData.author" /></div><div>需要修改/查询的数据主键(id):<el-input v-model="mainKey" /></div><div>需要查询的数据索引(title):<el-input v-model="mainTitle" /></div></el-col><el-col :span="8"> 查询结果:<br />{{ detailData }} </el-col></el-row></div>
</template><script>
export default {data() {return {formData: {title: '',author: ''},mainKey: null,mainTitle: '',detailData: null}},created() {this.initState()},methods: {initState() {// 打开(或创建)一个名为 "myDatabase" 的数据库const request = indexedDB.open('myDatabase', 1)// onupgradeneeded 是 IndexedDB API 中的一个事件,它在数据库的版本发生变化时被触发。这通常发生在你打开数据库时指定了一个比当前数据库版本更高的版本号request.onupgradeneeded = function(event) {const db = event.target.result// 创建一个名为 "books" 的对象存储const objectStore = db.createObjectStore('books', {keyPath: 'id', // 主键autoIncrement: true // 主键(keyPath)是否自动增长})// 创建索引createIndex(参数一:索引的名称(字符串);参数二:索引基于的键路径(字符串或数组);参数三:一个对象,包含索引的配置选项,如unique(是否唯一))objectStore.createIndex('title', 'title', { unique: false })}request.onerror = event => {console.error('数据库打开失败:' + event.target.errorCode)}},onOperation(type) {const _this = thisconst request = indexedDB.open('myDatabase', 1)request.onsuccess = function(event) {const db = event.target.result// 创建一个只读事务,涉及到 "books" 对象存储const transaction = db.transaction(['books'], 'readwrite')// 用于获取事务中的一个对象存储const objectStore = transaction.objectStore('books')// 增if (type === 'add') {objectStore.add(_this.formData)}// 删if (type === 'delete') {objectStore.delete(Number(_this.mainKey))}// 改if (type === 'update') {objectStore.put({id: Number(_this.mainKey),..._this.formData})}let getRequest// 查-主键if (type === 'query') {getRequest = objectStore.get(Number(_this.mainKey))// 查-索引} else if (type === 'queryIndex') {// 获取 "title" 索引const index = objectStore.index('title')getRequest = index.getAll(_this.mainTitle)} else {// 查-allgetRequest = objectStore.getAll()}getRequest.onsuccess = function(event) {_this.detailData = event.target.resultconsole.log('查询结果:', event.target.result)}}}}
}
</script>
三、存储
IndexedDB 是浏览器提供的一个客户端存储技术,它的数据存储在用户的设备上,而不是在服务器上。这意味着 IndexedDB 的数据是与设备绑定的,如果你更换了设备,之前设备上的 IndexedDB 数据不会自动迁移到新设备上。此外,IndexedDB 的数据也是与浏览器和域名绑定的。即使在同一台设备上,不同的浏览器或者不同的域名下的 IndexedDB 数据是相互隔离的。