Dexie.js 使用教程
Dexie.js 是一个基于 IndexedDB 的轻量级 JavaScript 库,它提供了更简单、更友好的 API 来操作浏览器中的 IndexedDB 数据库。下面是 Dexie.js 的基本使用教程。
1. 安装 Dexie.js
可以通过 npm 或直接通过 CDN 引入 Dexie.js:
npm 安装
npm install dexie
CDN 引入
<script src="https://unpkg.com/dexie@latest/dist/dexie.js"></script>
2. 创建数据库
// 创建或打开数据库
const db = new Dexie('MyDatabase');
// 定义数据库模式和版本
db.version(1).stores({
friends: '++id, name, age', // 主键是自增的id,索引有name和age
products: '++id, name, price'
});
3. 基本操作
添加数据
async function addFriend() {
try {
const id = await db.friends.add({
name: '张三',
age: 25,
email: 'zhangsan@example.com'
});
console.log(`添加成功,ID: ${id}`);
} catch (error) {
console.error('添加失败:', error);
}
}
查询数据
async function getFriends() {
// 获取所有朋友
const allFriends = await db.friends.toArray();
console.log(allFriends);
// 按条件查询
const youngFriends = await db.friends
.where('age').below(30)
.toArray();
console.log(youngFriends);
// 获取单个记录
const friend = await db.friends.get(1);
console.log(friend);
}
更新数据
async function updateFriend() {
try {
const updated = await db.friends.update(1, {
age: 26
});
if (updated) {
console.log('更新成功');
} else {
console.log('未找到记录');
}
} catch (error) {
console.error('更新失败:', error);
}
}
删除数据
async function deleteFriend() {
try {
await db.friends.delete(1);
console.log('删除成功');
} catch (error) {
console.error('删除失败:', error);
}
}
4. 高级查询
使用 where() 方法
async function complexQuery() {
// 年龄在20-30之间的朋友
const friends = await db.friends
.where('age').between(20, 30)
.toArray();
// 名字以"张"开头的朋友
const zhangFriends = await db.friends
.where('name').startsWith('张')
.toArray();
}
使用 each() 方法迭代
async function iterateFriends() {
await db.friends.each(friend => {
console.log(friend.name);
});
}
5. 事务处理
async function transactionExample() {
await db.transaction('rw', db.friends, db.products, async () => {
// 在这个事务中可以同时操作friends和products表
await db.friends.add({name: '李四', age: 28});
await db.products.add({name: '笔记本电脑', price: 5999});
}).catch(error => {
console.error('事务失败:', error);
});
}
6. 数据库升级
当需要修改数据库结构时,可以增加版本号:
db.version(2).stores({
friends: '++id, name, age, email', // 新增email字段
products: '++id, name, price, stock' // 新增stock字段
});
7. 使用索引
async function useIndex() {
// 使用name索引快速查询
const friend = await db.friends
.where('name').equals('张三')
.first();
// 复合索引查询
const friends = await db.friends
.where(['name', 'age']).equals(['张三', 25])
.toArray();
}
8. 错误处理
db.on('error', error => {
console.error('数据库错误:', error);
});
async function safeOperation() {
try {
await db.friends.add({name: '王五'});
} catch (error) {
console.error('操作失败:', error);
}
}
9. 使用 Promise 和 async/await
async function demo() {
try {
// 添加数据
await db.friends.add({name: '赵六', age: 30});
// 查询数据
const friends = await db.friends.toArray();
console.log(friends);
// 更新数据
await db.friends.where('name').equals('赵六').modify({age: 31});
} catch (error) {
console.error('发生错误:', error);
}
}
10. 关闭数据库
db.close();
总结
Dexie.js 大大简化了 IndexedDB 的使用,提供了更直观的 API 和强大的查询能力。通过本教程,你应该能够开始使用 Dexie.js 在浏览器中存储和操作数据了。更多高级功能可以参考 Dexie.js 官方文档。

浙公网安备 33010602011771号