IndexedDB是浏览器提供的支持索引、事务和异步操作的本地NoSQL数据库,适用于离线场景下持久化存储大量结构化数据,容量可达几百MB。

IndexedDB 是浏览器提供的本地数据库,适合在离线场景下持久化存储大量结构化数据。它比 localStorage 更强大:支持索引、事务、异步操作、二进制数据(如 Blob),且容量通常达几百 MB(具体取决于浏览器和用户设置)。
核心概念要先搞清
IndexedDB 不是传统 SQL 数据库,没有表、SELECT 语句,而是基于对象仓库(object store)、键路径(keyPath)、索引(index)和事务(transaction)的 NoSQL 模式:
- 数据库(IDBDatabase):整个 IndexedDB 实例,一个域名下可建多个,但需显式打开
- 对象仓库(Object Store):类似“表”,每个数据库可有多个,必须在版本升级时创建(不能运行时新增)
- 键(Key):每条记录的唯一标识,可以自动生成(autoIncrement)或由字段指定(keyPath)
- 索引(Index):在非主键字段上建立,用于快速查询(如按用户名查用户)
- 事务(IDBTransaction):所有读写操作必须在事务中进行,支持只读(readonly)和读写(readwrite)模式
基础用法:打开、建库、增删查
以下是一个完整示例,实现一个简单的待办事项(todo)存储:
1. 打开并初始化数据库
立即学习“Java免费学习笔记(深入)”;
首次打开会触发 onupgradeneeded,此时可建对象仓库和索引:
const DB_NAME = 'todoDB';
const DB_VERSION = 1;
const STORE_NAME = 'todos';
let db;
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => console.error('打开数据库失败');
request.onsuccess = (e) => {
db = e.target.result;
};
request.onupgradeneeded = (e) => {
const newDb = e.target.result;
// 创建对象仓库,主键为 id 字段(自动递增)
const store = newDb.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
// 在 title 字段上建索引,方便按标题搜索
store.createIndex('byTitle', 'title', { unique: false });
};
2. 添加一条数据
function addTodo(todo) {
const tx = db.transaction(STORE_NAME, 'readwrite');
const store = tx.objectStore(STORE_NAME);
const req = store.add({ ...todo, createdAt: Date.now() });
req.onsuccess = () => console.log('添加成功');
req.onerror = () => console.error('添加失败');
}
// 调用:addTodo({ title: '买牛奶', done: false });
3. 查询全部或按条件查
// 查全部
function getAllTodos() {
const tx = db.transaction(STORE_NAME, 'readonly');
const store = tx.objectStore(STORE_NAME);
const req = store.getAll();
req.onsuccess = (e) => console.log(e.target.result); // 返回数组
}
// 按 title 精确查找(使用索引)
function findTodoByTitle(title) {
const tx = db.transaction(STORE_NAME, 'readonly');
const store = tx.objectStore(STORE_NAME);
const index = store.index('byTitle');
const req = index.get(title);
req.onsuccess = (e) => console.log(e.target.result);
}
实用技巧与避坑点
实际开发中容易踩的几个坑,注意绕开:
- 版本升级不能跳过中间版:比如当前是 v1,想升到 v3,必须依次触发 v2 和 v3 的 onupgradeneeded;否则旧版逻辑可能丢失
- 事务生命周期很短:事务在事件循环结束前自动关闭,不要把异步操作(如 fetch、setTimeout)放在事务回调外再操作 store
- 主键不能重复,但 keyPath 字段可为空:若设了 keyPath: 'id',又传入 { title: 'xxx' }(无 id),会报错;可改用 autoIncrement 或手动生成 id
- 删除数据库用 indexedDB.deleteDatabase('name'),调试时可手动清除(DevTools → Application → Storage → Clear site data)
配合离线场景的典型流程
做 PWA 或离线应用时,常见组合是:网络正常时同步到服务端,断网时写入 IndexedDB,恢复后自动补传:
- 监听 navigator.onLine 变化,切换数据源(API / IDB)
- 封装统一的 CRUD 方法,内部自动判断连通性
- 用 Service Worker 拦截请求,对失败的 POST/PUT 请求存入 IDB 队列,再轮询重发
- 避免直接在 UI 层调用 IDB API,建议用 Promise 封装(或用 idb 这类轻量库简化写法)
基本上就这些。IndexedDB 学起来门槛略高,但一旦掌握,离线能力就稳了。不需要追求一步到位,从一个对象仓库开始,边用边补索引和事务逻辑,很快就能上手。











