Vue 2 Tutorial- How To Integrate Cloud Firestore With VueFire

In this Vue 2 tutorial, we will learn how to integrate Cloud Firestore Database in Vue Application using the VueFire Package. This is a step-by-step Vue.js and Firebase tutorial.

 

The Cloud Firestore helps store and sync the data in real-time across all connected devices. We will use the VueFire Package to take advantage of Firebase. It makes our development work quite simple by giving direct access to Firebase objects.

 

The Vuefire offers logical solutions to create real-time bindings between a Firebase RTDB or a Firebase Cloud Firestore and our Vue application. It always keeps our local data in sync with the remote database.

Firebase is a widely used database cloud infrastructure for client-side apps. It offers powerful features to manage the backend. We can easily create APIs and collect data on the cloud database.

It can be used with other frameworks and platforms such as Angular, React Android, or iOS.

 

Below-given are some of the core server-side features that we can easily get with Firebase:

  • Cloud storage
  • Real-time update
  • Easy A/B testing
  • Analytics monitoring
  • Authentication report
  • Easy server management
  • Real-time communication
  • offline access to WEB SDK
  • Hosting and cloud storage
  • Push notification support
  • Straightforward app hosting
  • Google Cloud IoT tools integration support

 

Step 1- Set Up Vue Project With Vue CLI

The very basic step for starting with the implementation is just to install the Vue CLI 4 on our development system:

npm install -g @vue/cli

 

The next step is just to install the Vue project using the given command:

vue create vue-firebase-setup

 

Now, Vue CLI will ask about our preferences and we may go with the below configurations:

 

Select “Manually select features”

Then, we choose “Router” “Vuex” and “CSS Pre-processors”.

 

Error: digital envelope routines::unsupported
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

 

To remove the above error for invoking the app, do remember to update the “scripts”: [] array in the package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

 

Step 2- Vue Multi-Word Error

To remove the multi-word error warning, we need to add the following code in the vue.config.js file:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
})

We are all good to start the app on the localhost server. After that, we will get inside the project folder and run the below command:

npm run serve

 

Step 3- Install & Configure VueFire Package In Vue

VueFire makes it quite easy and smooth to bind firestore collections and documents and keep our local data always up to date with their remote versions.

 

Further, we will install firebase and vuefire modules in the Vue app using either NPM or Yarn:

npm i firebase@^8.10.0 vuefire

 

Afterward, we need to configure Firebase in the Vue app. For that, we go to the main.js file to facilitate the VueFire plugin:

// src/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { firestorePlugin } from 'vuefire'
Vue.use(firestorePlugin);
Vue.config.productionTip = false;
new Vue({
  router,
  store,
  render: function (h) { return h(App) }
}).$mount('#app')

 

Step 4- Setting Up A Firebase project

Here, we will be creating a Firebase project by following the below steps:

Firstly, we open the Firebase console.

Then, click “Create a project”.

Creating Firebase Project

Further, we will click on the “Add project” button after which we give our project a name.

enter your project name

Afterward, we need to add Firebase to Vue app. It offers iOS, Android, and Web options to get started. But we will be using the web options.

add Firebase to Vue app

Now, we have to enter the project name to register our Firebase app.

register your Firebase app

We will get the Firebase Configuration that we will need in a bit to make the connection between Vue and Firebase.

Firebase Config Keys

Next, we have to click on Database > cloud Firestore and then click on the “create database“.

We will configure secure rules for Cloud Firestore. We are using Start in test mode for demo purposes.

secure rules for Cloud Firestore

 

Step 5- Make Firebase and Vue.js Connection

In order to make the connection between Firebase and Vue.js, we need to create a new file in the Vue project. We will name it firebaseDatabase.js.

import * as firebase from 'firebase';
const firebaseConfig = {
    apiKey: "api-key",
    authDomain: "project-id.firebaseapp.com",
    databaseURL: "https://project-id.firebaseio.com",
    projectId: "project-id",
    storageBucket: "project-id.appspot.com",
    messagingSenderId: "sender-id",
    appId: "app-id",
    measurementId: "G-measurement-id"
}
const firebaseApp = firebase.initializeApp(firebaseConfig);
export const db = firebaseApp.firestore();

 

First of all, we have to take the Firebase configuration and define the object for it.

Then, we set the firebase configuration details as an argument in the Firebase.initializeApp(firebaseConfig) method.

Lastly, we export the firebase database for all the Vue components.

 

Step 6- Access Cloud Firestore Via Vue.js To Display Data

Now, we are ready to retrieve data from the Firebase Database and display it to the web browser via the Vue component.

// views/Home.vue
<template>
  <ul>
    <li  v-for="student of students" :key="student['.key']">
      {{student.id}} <br>
      {{student.name}} <br>
      {{student.email}}
    </li>
  </ul>
</template>
<script>
import { db } from '../firebaseDatabase';
export default {
  components: {
      name: 'Home'
  },
  data() {
    return {
      students: []
    }
  },
  created: function() {
      db.collection('students').get()
      .then(snapshot => {
        snapshot.forEach(doc => {
          let item = doc.data()
          item.id = doc.id
          this.students.push(item)
        })
      })
  }  
}
</script>

 

We know that components are reusable instances. Vue components are sturdy instances. They accept data, computed, watch, methods, and lifecycle hooks.

By using the lifecycle hook, we get the data from the firebase collection and inserted in the students array.

To verify the Firebase implementation in the Vue app, we will start the app using the below command:

npm run serve

 

Conclusion

So, friends, we have seen how to integrate Cloud Firestore with VueFire in a Vue 2 application.

 

Thanks

Leave a Reply

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