快速开始
这份文档只做一件事:帮你用最短路径跑通 RxDB 的本地数据链路。
第一次接触时,不要先看同步、分支、协作。先跑通这条主线:模型定义 → 本地数据库 → 查询 → 写入 → UI 绑定。当前仓库里最稳定、最容易验证的也是这一段。
本页重点
- 先验证 SQLite / PGlite 的本地执行能力
- 先理解实体模型、查询和写入 API
- 框架层只负责把同一套数据能力接到 Angular / React / Vue
- 版本协作与远程同步放到第二阶段再看
跑通后你会确认
- 浏览器内关系型数据库能力
- 响应式查询与数据写入链路
- 类型安全的实体模型
- Angular / React / Vue 三套对等接口
想先看现成应用
仓库根目录已经有可运行的 demo:
pnpm nx serve dev-rxdb-angular
pnpm nx serve dev-rxdb-react
pnpm nx serve dev-rxdb-vue
如果你更想先理解最小接入代码,再继续看下面的安装与初始化示例。
推荐阅读顺序
建议按这个顺序读:
这个顺序能先建立数据层心智,再决定框架和适配器怎么选。
安装
核心包
- npm
- Yarn
- pnpm
- Bun
npm install @aiao/rxdb @aiao/rxdb-adapter-sqlite
yarn add @aiao/rxdb @aiao/rxdb-adapter-sqlite
pnpm add @aiao/rxdb @aiao/rxdb-adapter-sqlite
bun add @aiao/rxdb @aiao/rxdb-adapter-sqlite
框架集成(可选)
根据使用的前端框架选择对应的集成包:
- npm
- Yarn
- pnpm
- Bun
# React
npm install @aiao/rxdb-react
# Vue 3
npm install @aiao/rxdb-vue
# Angular
npm install @aiao/rxdb-angular
# React
yarn add @aiao/rxdb-react
# Vue 3
yarn add @aiao/rxdb-vue
# Angular
yarn add @aiao/rxdb-angular
# React
pnpm add @aiao/rxdb-react
# Vue 3
pnpm add @aiao/rxdb-vue
# Angular
pnpm add @aiao/rxdb-angular
# React
bun add @aiao/rxdb-react
# Vue 3
bun add @aiao/rxdb-vue
# Angular
bun add @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 }
});
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' }) : undefined,
sharedWorker: !available,
sharedWorkerInstance:
!available ? new SharedWorker(new URL('./sqlite-shared.worker', import.meta.url), { type: 'module' }) : undefined,
wasmPath: available ? '/wa-sqlite/wa-sqlite.wasm' : '/wa-sqlite/wa-sqlite-async.wasm'
});
});
await rxdb.connect('sqlite');
上面示例会根据浏览器能力自动选择更合适的 VFS 与 Worker 方案,优先使用 OPFS 获得更好的持久化表现。
3. 使用数据库
基础 CRUD 操作
import { firstValueFrom } from 'rxjs';
// 创建新记录
const todo = new Todo();
todo.title = '完成 RxDB 文档';
todo.createdAt = new Date();
await todo.save();
// 查询数据
const todos = await firstValueFrom(
Todo.find({
where: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: false }]
},
orderBy: [{ field: 'createdAt', sort: 'desc' }]
})
);
// 更新数据
todo.completed = true;
await todo.save();
// 删除数据
await todo.remove();
响应式查询
使用 RxJS 订阅数据变化:
import { Subscription, switchMap } from 'rxjs';
// 订阅查询结果
const subscription: Subscription = rxdb
.pipe(
switchMap(() =>
Todo.find({
where: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: false }]
}
})
)
)
.subscribe({
next: todos => {
console.log('未完成的待办:', todos);
},
error: err => {
console.error('查询错误:', err);
}
});
// 取消订阅
subscription.unsubscribe();
如果你只想先验证链路是否打通,做到这一步已经够了。接下来再接框架层,把 Observable 查询结果绑定到界面。
接下来怎么继续
框架集成
RxDB 为主流前端框架提供同一套心智模型。差别主要在 UI 绑定层,数据模型与查询结构保持一致。
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>
);
}
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>
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;
}
下一步建议
- 阅读安装细节与环境要求:安装说明
- 学习如何设计实体关系与索引:模型定义
- 了解查询、事务和实时更新:模型查询
- 查看跨框架演示页面:使用
pnpm nx serve dev-rxdb-angular等命令启动各框架演示
下一步
现在你已经了解了 RxDB 的基础使用,接下来可以:
- 了解模型定义 - 学习如何定义复杂的数据模型
- 学习模型查询 - findOne - 掌握单条记录查询
- 学习模型查询 - find - 掌握多条记录查询
- 配置 PGlite 适配器 - 使用 PostgreSQL 数据库
- 配置 SQLite 适配器 - 使用 SQLite 数据库
- React 集成 - 在 React 中使用
- Vue 集成 - 在 Vue 中使用
- Angular 集成 - 在 Angular 中使用
- 使用客户端生成器 - 自动生成类型安全的代码