跳到主要内容

快速开始

RxDB 是一个响应式数据库,通过 WebAssembly 技术在浏览器中提供完整的关系型数据库功能,让 Web 应用获得接近原生 App 的流畅与可靠体验。

安装

核心包

npm install @aiao/rxdb @aiao/rxdb-adapter-sqlite

框架集成(可选)

根据使用的前端框架选择对应的集成包:

# React
npm install @aiao/rxdb-react

# Vue 3
npm install @aiao/rxdb-vue

# Angular
npm install @aiao/rxdb-angular

基本使用

1. 定义数据模型

import { Entity, EntityBase, PropertyType } from '@aiao/rxdb';

@Entity({
name: 'Todo',
properties: [
{ name: 'title', type: PropertyType.string, required: true },
{ name: 'completed', type: PropertyType.boolean, default: false },
{ name: 'createdAt', type: PropertyType.date }
]
})
export class Todo extends EntityBase {}

2. 初始化数据库

import { RxDB, SyncType } from '@aiao/rxdb';
import { RxDBAdapterSqlite } from '@aiao/rxdb-adapter-sqlite';
import { checkOPFSAvailable } from '@aiao/utils';

// 创建数据库实例
const rxdb = new RxDB({
dbName: 'myapp',
entities: [Todo],
sync: {
local: { adapter: 'sqlite' },
type: SyncType.None
}
});

// 注册 SQLite 适配器
rxdb.adapter('sqlite', async db => {
const available = await checkOPFSAvailable();

return new RxDBAdapterSqlite(db, {
vfs: available ? 'OPFSCoopSyncVFS' : 'IDBBatchAtomicVFS',
worker: available,
workerInstance:
available ?
new Worker(new URL('./sqlite.worker', import.meta.url), {
type: 'module',
name: 'rxdb-worker'
})
: undefined,
sharedWorker: !available,
sharedWorkerInstance:
!available ?
new SharedWorker(new URL('./sqlite-shared.worker', import.meta.url), {
type: 'module',
name: 'rxdb-shared-worker'
})
: undefined,
wasmPath: available ? '/wa-sqlite/wa-sqlite.wasm' : '/wa-sqlite/wa-sqlite-async.wasm'
});
});

// 连接数据库
await rxdb.connect('sqlite').toPromise();

3. 使用数据库

基础 CRUD 操作

// 创建新记录
const todo = new Todo();
todo.title = '完成 RxDB 文档';
todo.createdAt = new Date();
await todo.save();

// 查询数据
const todos = await Todo.find({
where: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: false }]
},
orderBy: [{ field: 'createdAt', sort: 'desc' }]
}).toPromise();

// 更新数据
todo.completed = true;
await todo.save();

// 删除数据
await todo.remove();

响应式查询

使用 RxJS 订阅数据变化:

import { Subscription } from 'rxjs';

// 订阅查询结果
const subscription: Subscription = Todo.find({
where: { completed: false }
}).subscribe({
next: todos => {
console.log('未完成的待办:', todos);
},
error: err => {
console.error('查询错误:', err);
}
});

// 取消订阅
subscription.unsubscribe();

框架集成

RxDB 提供了主流前端框架的集成方案,让你可以轻松在应用中使用响应式数据库。

React 集成

import { RxDBProvider, useFind } from '@aiao/rxdb-react';

// 使用上面初始化的 rxdb 和定义的 Todo 实体

function App() {
return (
<RxDBProvider db={rxdb}>
<TodoList />
</RxDBProvider>
);
}

function TodoList() {
const {
value: todos,
isLoading,
isEmpty
} = useFind(Todo, {
where: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: false }]
},
orderBy: [{ field: 'createdAt', sort: 'desc' }]
});

if (isLoading) return <div>加载中...</div>;
if (isEmpty) return <div>暂无待办事项</div>;

return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
}

查看完整 React 集成文档 →

Vue 集成

<script setup lang="ts">
import { useFind } from '@aiao/rxdb-vue';

// 使用上面定义的 Todo 实体

const {
value: todos,
isLoading,
isEmpty
} = useFind(Todo, {
where: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: false }]
},
orderBy: [{ field: 'createdAt', sort: 'desc' }]
});
</script>

<template>
<div v-if="isLoading">加载中...</div>
<div v-else-if="isEmpty">暂无待办事项</div>
<ul v-else>
<li v-for="todo in todos" :key="todo.id">
{{ todo.title }}
</li>
</ul>
</template>

查看完整 Vue 集成文档 →

Angular 集成

import { Component } from '@angular/core';
import { provideRxDB, useFind } from '@aiao/rxdb-angular';

// 使用上面定义的 Todo 实体

@Component({
selector: 'app-todo-list',
standalone: true,
template: `
@if (isLoading()) {
<div>加载中...</div>
} @else if (isEmpty()) {
<div>暂无待办事项</div>
} @else {
<ul>
@for (todo of todos(); track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
}
`
})
export class TodoListComponent {
private resource = useFind(Todo, {
where: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: false }]
},
orderBy: [{ field: 'createdAt', sort: 'desc' }]
});

todos = this.resource.value;
isLoading = this.resource.isLoading;
isEmpty = this.resource.isEmpty;
}

查看完整 Angular 集成文档 →

下一步

现在你已经了解了 RxDB 的基础使用,接下来可以: