使用第三方库访问IndexDB:Dexie.js

1,674 阅读1分钟

IndexDB的封装库:Dexie.js

  • vue项目安装dexie依赖
npm i dexie
  • 创建数据库:新建db.js或db.ts
// db.js
import Dexie from 'dexie';

export const db = new Dexie('myDatabase');
db.version(1).stores({
  friends: '++id, name, age', // Primary key and indexed props
});
// db.ts
import Dexie, { Table } from 'dexie';

export interface Friend {
  id?: number;
  name: string;
  age: number;
}

export class MySubClassedDexie extends Dexie {
  // 'friends' is added by dexie when declaring the stores()
  // We just tell the typing system this is the case
  friends!: Table<Friend>; 

  constructor() {
    super('myDatabase');
    this.version(1).stores({
      friends: '++id, name, age' // Primary key and indexed props
    });
  }
}

export const db = new MySubClassedDexie();
  • 增删改查
import { db } from '../db';

......

// 增加数据
const id = await db.friends.add({
    name: 'Tom',
    age: 18,
});
// 删除数据
await db.friends.delete(id);
// 修改数据
await db.friends.put({
    name: 'Alice',
    age: 18,
});
// 查询数据
const friend = await db.friends.get(id);
  • 高级查询
// 例:查询年龄小于25的
await db.friends.where("age").below(25).toArray();

如下图是可选的方法: image.png

  • 关闭数据库
db.close();
  • 删除数据库
db.delete();