Skip to content

useRTDB

类别
导出大小
243 B
@vueuse/firebase
最近修改
2 days ago

响应式 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

选项类型默认值描述
autoDisposebooleantrue组件卸载时自动取消订阅
errorHandler(err: Error) => voidconsole.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>