VueFire Documentation

repository·main·Indexed 26 days ago

https://github.com/vuejs/vuefire

Official Firebase bindings for Vue.js (version 3.2.3) that provide seamless reactivity and support for modern Firebase modular SDKs (v9+). Compatible with Vue 2.7 and Vue 3, supporting both Composition and Options APIs. Features include integration with Pinia and Vuex, support for Firestore and Realtime Database, and modules for Firebase App Check and Authentication.

Tokens
25.6K
Snippets
80
Records
164
Agent score
86%

What's inside VueFire

  1. Overview of VueFire

    main

    VueFire provides official Firebase bindings for Vue.js. It offers idiomatic composables designed for realtime data and other Firebase services, aligning with Vue's declarative approach.

    Key features include:

    • Idiomatic APIs: Uses composables that handle nested collections, document references, and more automatically.
    • Performance: VueFire manages the data binding to ensure state stays synchronized with the server while allowing full access to the Firebase JS SDK.
    • Flexibility: Supports Firebase Database, Firestore, Authentication, and more via tree-shakable APIs built on top of the Firebase modular JS SDK.
  2. Overview of VueFire features

    main

    VueFire is a library designed to make using Firebase with Vue easy. Key features include:

    • Compatibility: Works with Vue >=2.7 and Vue 3.
    • API Support: Supports both Composition and Options API.
    • State Management: Works with Vuex, Pinia, and any object providing a Vue ref().
    • Optimization: Built for Modular Firebase >=9 to enable optimal tree shaking.
    • Reactivity: Automatically listens for changes in nested references.
  3. Introduction to Vuefire

    main
    Vuefire is a pragmatic solution for creating realtime bindings between Firebase Realtime Database (RTDB) or Firebase Cloud Firestore and your Vue application. It simplifies the process of keeping local application state in sync with remote database changes, handling complex edge cases like data synchronization, listener management, and Firestore references automatically.
  4. Use References in Cloud Firestore

    main

    Cloud Firestore supports document references. To write a reference to another document, pass the actual reference object returned by the database instance.

    // Cloud Firestore only
    db.collection('books').add({
      name: '1984',
      author: db.collection('authors').doc('george-orwell'),
    })
  5. Set up the Nuxt Module for development

    main

    To develop with the Nuxt Module, you must first generate the necessary type stubs and then start the playground environment.

    1. Generate type stubs: npm run dev:prepare
    2. Start the playground: npm run dev
    npm run dev:prepare
    npm run dev
  6. Perform one-time reads using Firebase JS SDK

    main

    If you do not require real-time synchronization and only need to fetch data once, you can use the native Firebase JS SDK directly without Vuefire. This is useful for data that is not part of a component's reactive state.

    // Realtime Database (RTDB) one-time read
    // retrieve a collection
    db.ref('documents').once('value', snapshot => {
      const documents = snapshot.val()
      // do something with documents
    })
    
    // retrieve a document
    db.ref('documents/' + documentId).once('value', snapshot => {
      const document = snapshot.val()
      // do something with document
    })
    
    // Cloud Firestore one-time read
    // retrieve a collection
    db.collection('documents')
      .get()
      .then(querySnapshot => {
        const documents = querySnapshot.docs.map(doc => doc.data())
        // do something with documents
      })
    
    // retrieve a document
    db.collection('documents')
      .doc(documentId)
      .get()
      .then(snapshot => {
        const document = snapshot.data()
        // do something with document
      })
  7. Initialize VueFire in a Vue 3 application

    main

    To set up VueFire in a Vue 3 app, use the VueFire plugin with your initialized firebaseApp. You can also include additional modules like VueFireAuth() in the modules array.

    import { createApp } from 'vue'
    import { VueFire, VueFireAuth } from 'vuefire'
    import App from './App.vue'
    import { firebaseApp } from './firebase'
    
    const app = createApp(App)
    app.use(VueFire, {
      firebaseApp,
      modules: [
        VueFireAuth(),
      ],
    })
    
    app.mount('#app')
  8. Bind Firebase collections to existing Vue Refs

    main

    If you need to reuse an existing ref() (for example, one coming from a composable or a state management store like Pinia), you can pass that ref to the target option in the useCollection composable.

    When using the target option:

    1. The composable will use your provided ref instead of creating a new one.
    2. The composable will not return the ref in its result object. Instead, it returns an object containing metadata (such as pending).
    // given an existing Ref<Todo[]>
    todos 
    
    // Pass the existing ref to the 'target' option
    const { pending } = useCollection(todoListRef, { target: todos })
  9. Use Timestamps in Cloud Firestore

    main

    Cloud Firestore supports Timestamp objects. Realtime Database does not support this type. Import Timestamp from your database instance to convert standard JavaScript Dates into Firestore Timestamps.

    // Cloud Firestore only
    import { Timestamp } from './db'
    
    await db.collection('events').add({
      name: 'Prise de la Bastille',
      date: Timestamp.fromDate(new Date('1789-07-14')),
    })
  10. Initialize Firebase services in Nuxt

    main

    When using Nuxt, you can initialize Firebase services (like Analytics) by creating a plugin in the plugins/ directory.

    Important: Use the .client suffix for services that only run on the client side (e.g., analytics.client.ts) to ensure they are not executed during SSR.

    import {
      type Analytics,
      initializeAnalytics,
      isSupported,
    } from 'firebase/analytics'
    
    export default defineNuxtPlugin(async () => {
      const firebaseApp = useFirebaseApp()
    
      console.log('Loading analytics')
    
      let analytics: Analytics | null = null
      if (await isSupported()) {
        analytics = initializeAnalytics(firebaseApp)
        console.log('Loaded analytics')
      } else {
        console.log('Analytics not supported')
      }
    
      return {
        provide: {
          analytics,
        },
      }
    })