useFirestore
useFirestore
リアクティブな Firestore バインディング。リモートデータベースと常に同期を保つことを簡単にします。
使用法
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'))
// またはドキュメント参照の場合
const user = useFirestore(doc(db, 'users', 'my-user-id'))
// リアクティブなクエリに ref 値を使用することもできます
const postsLimit = shallowRef(10)
const postsQuery = computed(() => query(collection(db, 'posts'), orderBy('createdAt', 'desc'), limit(postsLimit.value)))
const posts = useFirestore(postsQuery)
// クエリが実行準備ができたときに知らせるためにブール値を使用できます
// 偽の値を取得すると、初期値を返します
const userId = shallowRef('')
const userQuery = computed(() => userId.value && doc(db, 'users', userId.value))
const userData = useFirestore(userQuery, null)
インスタンス間での共有
autoDispose: false を渡すことで db リファレンスを再利用できます。また、db リファレンスを自動破棄する前のミリ秒数を設定することもできます。
注意: 破棄されていない db リファレンスを再取得しても Firestore の読み取りコストはかかりません。
import { useFirestore } from '@vueuse/firebase/useFirestore'
import { collection } from 'firebase/firestore'
// ---cut---
const todos = useFirestore(collection(db, 'todos'), undefined, { autoDispose: false })
またはコアパッケージの createGlobalState を使用します
// @filename: store.ts
// ---cut---
// store.ts
import { createGlobalState } from '@vueuse/core'
import { useFirestore } from '@vueuse/firebase/useFirestore'
export const useTodos = createGlobalState(
() => useFirestore(collection(db, 'todos')),
)
<!-- app.vue -->
<script setup lang="ts">
// @include: store
// ---cut---
import { useTodos } from './store'
const todos = useTodos()
</script>
© 2019–PRESENT Anthony Fu https://github.com/antfu
※このページは Nuxt.js 公式ドキュメントの翻訳ページです。
公式ドキュメントの該当ページはこちら:
#