官网 https://dexie.org/docs/Typescript
简介
Dexie.js 用于简化了 IndexedDB 的使用。
IndexedDB 是一种在浏览器中进行持久化存储的 Web API,它允许你在用户的浏览器中存储大量结构化数据,并且可以对这些数据进行索引和查询。
安装
npm i dexie
创建数据库
import Dexie from 'dexie';
// 创建一个名为 myDB 的数据库
const db = new Dexie('myDB');
创建表
// 定义数据库版本和表结构
db.version(1).stores({
// 定义一个名为 friends 的表,以自增的 id 为主键,同时对 name 字段建立索引
friends: '++id, name'
});
新增数据
单条新增 add(新增的内容)
// 向 friends 表中插入一条数据
await db.friends.add({ name: 'John Doe', age: 30 })
批量新增 bulkAdd(新增的内容数组)
// 准备批量新增的数据
const newFriendsList = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
// 使用 bulkAdd 进行批量新增,返回新增数据的 id 数组
const newIDList = await db.users.bulkAdd(newFriendsList )
删除数据 delete(主键)
// 根据主键删除数据, result 为 true 则操作成功,否则失败
const result = await db.friends.delete(1)
根据主键范围批量删除
// 删除主键 id 从 3 到 5 的记录
db.friends.where('id').between(3, 5).delete()
根据字段值批量删除
// 删除 age 字段值小于 35 的所有记录
db.friends.where('age').below(35).delete()
清空数据
// 删除 friends 表中的所有记录
db.friends.clear()
修改数据 update(主键,修改的内容)
// result 为 true 则更新成功,否则失败
const result = await db.friends.update(1, { age: 31 })
批量修改符合特定条件的数据
// 批量修改薪资低于 5000 的员工薪资
db.salaries.where('salary').below(5000)
.modify((salaryRecord) => {
salaryRecord.salary = 5000;
})
批量修改整个表的数据
// 批量修改整个表的数据,将所有员工薪资提高 10%
db.salaries.toCollection()
.modify((salaryRecord) => {
salaryRecord.salary = salaryRecord.salary * 1.1;
})
批量修改数组中的数据
// 模拟要修改的数据数组
const updateDataArray = [
{ id: 1, newSalary: 6000 },
{ id: 2, newSalary: 6500 }
];
// 开启事务进行批量修改
db.transaction('rw', db.salaries, async () => {
try {
for (const data of updateDataArray) {
await db.salaries.update(data.id, { salary: data.newSalary });
}
console.log('批量修改数据成功');
} catch (error) {
console.error('批量修改数据失败:', error);
}
});
查询数据
查询单条数据 get(主键)
// 根据主键查询 id 为 1 的数据
const friendDetail = await db.friends.get(1)
查询多条数据 toArray()
// 查询所有数据,得到一个数组
const friendList = await db.friends.toArray()
添加查询条件
// 查询年龄大于 25 的数据
const friendList_filtered = db.friends.where('age').above(25).toArray()
// 多条件查询示例:查询年龄在 25 到 35 岁之间且部门为 "IT" 的员工
db.employees.where('age').between(25, 35)
.and(employee => employee.department === 'IT')
.toArray()
统计数量 count()
// 获取员工总数
const count = await db.employees.count();
事务操作 transaction
将一系列操作组合在一起,要么全部成功执行,要么全部不执行,保证了数据的一致性和完整性。
// 开启一个读写事务,操作 friends 表
db.transaction('rw', db.friends, async () => {
try {
// 插入数据
await db.friends.add({ name: 'Jane Smith', age: 28 });
// 查询数据
const friends = await db.friends.toArray();
console.log('事务中的数据:', friends);
} catch (error) {
console.error('事务操作失败:', error);
}
});