主题
useRTDB
响应式 Firebase Realtime Database 绑定。使得 始终保持本地数据与远程数据库同步 变得简单。
🌐 Reactive Firebase Realtime Database binding. Making it straightforward to always keep your local data in sync with remotes databases. Available in the @vueuse/firebase add-on.
用法
🌐 Usage
ts
import { useRTDB } from '@vueuse/firebase/useRTDB'
import { initializeApp } from 'firebase/app'
import { getDatabase } from 'firebase/database'
const app = initializeApp({ /* config */ })
const db = getDatabase(app)
// in setup()
const todos = useRTDB(db.ref('todos'))选项
🌐 Options
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
autoDispose | boolean | true | 组件卸载时自动取消订阅 |
errorHandler | (err: Error) => void | console.error | 数据库错误的自定义错误处理器 |
返回值
🌐 Return Value
返回一个 Ref<T | undefined>,当数据库值更改时会自动更新。
🌐 Returns a Ref<T | undefined> that is automatically updated when the database value changes.
重用数据库引用
🌐 Reusing Database References
你可以通过传入 autoDispose: false 来重用数据库引用
🌐 You can reuse the db reference by passing autoDispose: false
ts
const todos = useRTDB(db.ref('todos'), { autoDispose: false })或者使用核心包中的 createGlobalState
🌐 or use createGlobalState from the core package
ts
// store.ts
import { createGlobalState } from '@vueuse/core'
import { useRTDB } from '@vueuse/firebase/useRTDB'
export const useTodos = createGlobalState(
() => useRTDB(db.ref('todos')),
)vue
<!-- app.vue -->
<script setup lang="ts">
import { useTodos } from './store'
const todos = useTodos()
</script>