Skip to content

useRTDB

类别
导出体积
243 B
依赖包
@vueuse/firebase
上次更改
7 minutes ago

响应式的 Firebase 实时数据库 绑定。使得始终将本地数据与远程数据库同步变得简单直观。 Available in the @vueuse/firebase add-on.

用法

ts
import { 
useRTDB
} from '@vueuse/firebase/useRTDB'
import {
initializeApp
} from 'firebase/app'
import {
getDatabase
} from 'firebase/database'
const
app
=
initializeApp
({ /* 配置 */ })
const
db
=
getDatabase
(
app
)
// 在 setup() 中 const
todos
=
useRTDB
(
db
.ref('todos'))

选项

选项类型默认值说明
autoDisposebooleantrue组件卸载时是否自动取消订阅
errorHandler(err: Error) => voidconsole.error数据库错误的自定义处理函数

返回值

返回一个 Ref<T | undefined>,该引用会在数据库值更改时自动更新。

复用数据库引用

你可以通过传递 autoDispose: false 来复用数据库引用。

ts
const 
todos
= useRTDB(db.ref('todos'), {
autoDispose
: false })

或者使用核心包中的 createGlobalState

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>

类型声明

ts
export interface UseRTDBOptions {
  
errorHandler
?: (
err
: Error) => void
autoDispose
?: boolean
} /** * Reactive Firebase Realtime Database binding. * * @see https://vueuse.org/useRTDB */ export declare function
useRTDB
<
T
= any>(
docRef
:
DatabaseReference
,
options
?: UseRTDBOptions,
):
Ref
<
T
| undefined,
T
| undefined>

源码

源码文档

贡献者

一纸忘忧

更新日志

没有最近的更新日志