主题
useFirestore
响应式 Firestore 绑定。让你可以轻松 始终保持本地数据与远程数据库同步。
🌐 Reactive Firestore 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 { useFirestore } from '@vueuse/firebase/useFirestore'
import { initializeApp } from 'firebase/app'
import { collection, doc, getFirestore, limit, orderBy, query } from 'firebase/firestore'
import { computed, shallowRef } from 'vue'
const app = initializeApp({ projectId: 'MY PROJECT ID' })
const db = getFirestore(app)
const todos = useFirestore(collection(db, 'todos'))
// or for doc reference
const user = useFirestore(doc(db, 'users', 'my-user-id'))
// you can also use ref value for reactive query
const postsLimit = shallowRef(10)
const postsQuery = computed(() => query(collection(db, 'posts'), orderBy('createdAt', 'desc'), limit(postsLimit.value)))
const posts = useFirestore(postsQuery)
// you can use the boolean value to tell a query when it is ready to run
// when it gets falsy value, return the initial value
const userId = shallowRef('')
const userQuery = computed(() => userId.value && doc(db, 'users', userId.value))
const userData = useFirestore(userQuery, null)返回值
🌐 Return Value
- 对于 文档参考:返回
Ref<T | null>(具有id属性的单个文档) - 对于 Query:返回
Ref<T[]>(文档数组,每个文档都有id属性)
文档 id 会自动作为只读属性添加到每个返回的文档中。
🌐 The document id is automatically added as a read-only property to each returned document.
选项
🌐 Options
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
errorHandler | (err: Error) => void | console.error | 自定义错误处理函数 |
autoDispose | boolean | number | true | 在作用域销毁时自动取消订阅。传入数字以延迟销毁(毫秒)。 |
错误处理
🌐 Error Handling
ts
const todos = useFirestore(collection(db, 'todos'), [], {
errorHandler: (err) => {
console.error('Firestore error:', err)
// Handle error (e.g., show notification)
},
})跨实例共享
🌐 Share across instances
你可以通过传递 autoDispose: false 来重用数据库引用。你也可以设置在自动释放数据库引用前的毫秒数。
🌐 You can reuse the db reference by passing autoDispose: false. You can also set an amount of milliseconds before auto disposing the db reference.
注意:再次获取未处理的数据库引用不需要 Firestore 读取。
🌐 Note : Getting a not disposed db reference again don't cost a Firestore read.
ts
const todos = useFirestore(collection(db, 'todos'), undefined, { autoDispose: false })或者使用核心包中的 createGlobalState
🌐 or use createGlobalState from the core package
ts
// store.ts
import { createGlobalState } from '@vueuse/core'
import { useFirestore } from '@vueuse/firebase/useFirestore'
export const useTodos = createGlobalState(
() => useFirestore(collection(db, 'todos')),
)vue
<!-- app.vue -->
<script setup lang="ts">
import { useTodos } from './store'
const todos = useTodos()
</script>