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

IndexedDB 是浏览器提供的本地数据库,适合在离线场景下持久化存储大量结构化数据。它比 localStorage 更强大:支持索引、事务、异步操作、二进制数据(如 Blob),且容量通常达几百 MB(具体取决于浏览器和用户设置)。
IndexedDB 不是传统 SQL 数据库,没有表、SELECT 语句,而是基于对象仓库(object store)、键路径(keyPath)、索引(index)和事务(transaction)的 NoSQL 模式:
以下是一个完整示例,实现一个简单的待办事项(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);
}
实际开发中容易踩的几个坑,注意绕开:
做 PWA 或离线应用时,常见组合是:网络正常时同步到服务端,断网时写入 IndexedDB,恢复后自动补传:
基本上就这些。IndexedDB 学起来门槛略高,但一旦掌握,离线能力就稳了。不需要追求一步到位,从一个对象仓库开始,边用边补索引和事务逻辑,很快就能上手。
以上就是如何实现离线存储_javascript中indexeddb怎么用?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号