Skip to content

Vuefire – Hướng dẫn sử dụng (Code Template)

Installation

npm install vuefire firebase

Realtime DB & Firestore

  • Install firestorePlugin = Cloud Firestore 
  • Install rtdbPlugin = (Real Time Database)
import Vue from 'vue'
import { firestorePlugin } from 'vuefire'

Vue.use(firestorePlugin)

main.js

import firebase from 'firebase/app'
import 'firebase/firestore'

// Get a Firestore instance
export const db = firebase
  .initializeApp({ projectId: 'MY PROJECT ID' })
  .firestore()

// Export types that exists in Firestore
// This is not always necessary, but it's used in other examples
const { Timestamp, GeoPoint } = firebase.firestore
export { Timestamp, GeoPoint }

// if using Firebase JS SDK < 5.8.0
db.settings({ timestampsInSnapshots: true })

db.js

Binding

  • Programmatic
  • Declarative

Programmatic

// UserProfile.vue
const users = db.collection('users')

export default {
  props: ['id'],
  data() {
    return {
      user: null,
    }
  },

  watch: {
    id: {
      // call it upon creation too
      immediate: true,
      handler(id) {
        this.$bind('user', users.doc(id))
      },
    },
  },
}
firestorertdb
$bind$rtdbBind
$unbind$rtdbUnbind

No need to call $rtdbUnbind/$unbind as $rtdbBind/$bind will automatically unbind any existing binding on the provided key. Upon component removal, all bindings are removed as well, so no need to use $rtdbUnbind/$unbind in destroyed hooks.

this.$bind('user', users.doc(this.id)).then(user => {
  this.user === user // true
})

this.$bind('documents', documents.where('creator', '==', this.id)).then(documents => {
  this.documents === documents // true
})

Unbind

this.$unbind('user')
this.$unbind('user', true)
// this.user === null

// keep current value
this.$unbind('user', false)
// this.user === { name: 'Eduardo' }

// to customize the value
this.$unbind('user', () => ({ name: 'unregistered' }))
// this.user === { name: 'unregistered' }

// for collections, they are reset to an empty array by default instead of `null`
this.$unbind('documents')
// this.documents === []

reset with bind

await this.$bind('user', userRef)
this.$bind('user', otherUserRef, { reset: false })

// while the user is fetched
// this.user === { name: 'Eduardo' }

Declarative

// RecentDocuments.vue
import { db } from './db'

export default {
  data() {
    return {
      documents: [],
    }
  },

  firestore: {
    documents: db.collection('documents'),
  },
}

ID của doc không thể sửa

Vuefire will retain it’s id in the Database as a non-enumerable (read-only)

this.user.id // jORwjIykFn1NmkdzTkhU
// the id is non enumerable
Object.keys(this.user).includes('id') // false

Special Datatype

Geopoint

import { GeoPoint } from './db'

await db.collection('cities').add({
  name: 'Paris',
  location: new GeoPoint(48.8588377, 2.2770206),
})

const paris = this.cities[this.cities.length - 1]
paris.location.latitude // 48.8588377
paris.location.longitude // 2.2770206

Timestamp

import { Timestamp } from './db'

await db.collection('events').add({
  name: 'Prise de la Bastille',
  date: Timestamp.fromDate(new Date('1789-07-14')),
})

const prise = this.events[this.events.length - 1]
prise.date.seconds // -5694969600
prise.date.nanoseconds // 0
prise.toDate() // Tue Jul 14 1789

Reference

Vuefire will stop at that level (2 level nesting)

{
  name: 'Jessica',
  documents: [
    db.collection('documents').doc('gift-list'),
  ],
}
{
  content: '...',
  sharedWith: [
    db.collection('users').doc('2'),
    db.collection('users').doc('3'),
  ]
}

// override the default value of 2 for maxRefDepth
this.$bind('user', db.collection('users').doc('1'), { maxRefDepth: 1 })

Query

One time read(firestore)

// 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
  })

Sorting

firebase: {
    documents: db.collection('documents').orderBy('createdAt'),
}

or

this.$bind('documents', db.collection('documents').orderBy('createdAt'))

Filter

this.$bind('documents', db
    .collection('documents')
    .where('wordCount', '>', 200)
    .orderBy('wordCount')
)

Write

db.collection('users')
  .doc(this.user.id)
  .set(user)
  .then(() => {
    console.log('user updated!')
  })
// we can also use `$firestoreRefs.user` to refer to the bound user reference
this.$firestoreRefs.user.set(user)

update

this.$firestoreRefs.user.update({ lastName: newLastName }).then(() => {
  console.log('user updated!')
})

remove

db.collection('cities')
  .doc(cityId)
  .delete()
this.$firestoreRefs.cities.doc(cityId).delete()
this.$firestoreRefs.selectedCity.delete()

add doc to collection

db.collection('cities').add({
  name: 'Fuengirola',
  slogan: 'Un sol de ciudad',
})
this.$firestoreRefs.cities.add({
  name: 'Paris',
  slogan: 'La Ville lumière',
})

Ref

db.collection('books').add({
  name: '1984',
  author: db.collection('authors').doc('george-orwell'),
})

GeoPoint

location: new GeoPoint(48.8588377, 2.2770206),

Date

date: Timestamp.fromDate(new Date('1789-07-14'))

or current

createdAt: firebase.firestore.FieldValue.serverTimestamp()
Published inFirebase

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *