Vue 2 Firebase: How To Build Vue CRUD App With Cloud Firestore

This Vue 2 tutorial will show us how to build a Vue js CRUD web application using the Firebase database.

Build Vue CRUD App with Cloud Firestore

In this Vue example, we will create a basic customer records management system in which a user can perform CRUD operations and store the data in the Cloud Firestore.

 

Firebase reduces the pain of maintaining the backend server because Firebase is a Backend-as-a service. It gives freedom to develop to focus on enhancing the user experience rather than maintaining the backend or server.

 

Below given are some of the Firebase features:

  • Push Notifications
  • Enhanced Security
  • Cloud Storage
  • Ready-made API
  • Analytics Monitoring
  • Easy Server Management
  • Easy A/B Testing
  • Hosting And Cloud Storage
  • Realtime Data Update
  • Authentication With Email & Password, Google, Facebook, & Github

 

Let’s learn below step by step how to build a Vue CRUD application with Node and Express.js:

Step 1- Prerequisites

Step 2- Setting Up Firebase Project

Step 3- Create Vue App With Vue CLI

Step 4- Add Bootstrap

Step 5- creating Vue Components

Step 6- Create Vue Router For Firebase CRUD Demo App

Step 7- Add Navigation With router View

Step 8- Create Interactive Vue Form With Bootstrap

Step 9- Install And Set Up Firebase

Step 10- Add Data To Cloud Firestore

Step 11- Display Data & Delete data Object

Step 12- Update Data

Step 13- Deploy Vue App On Firebase Hosting

Step 14- Conclusion

 

Step 1- Prerequisites

First of all, we need the following tools and frameworks:

  1. Vue CLI
  2. Vue
  3. Firebase
  4. Bootstrap 5
  5. IDE or Code Editor

 

Step 2- Setting Up Firebase Project

We need Firebase configuration details to connect Firebase with the Vue.js app. So, in this step, we will create a Firebase project inside the firebase dashboard.

For this, we need to place the URL console.firebase.google.com on the browser’s address bar and press enter. Doing this will take us to the Firebase official website:

 

Firstly, we will click “create a project”.

Then, we click “Add project”, we need not enable analytics for this demo:

Setting up Firebase Project

Further, we click “Continue” to generate the project:

project name

Then, we will click on the web icon:

Firebase web icon

Afterward, we will provide the app nickname and click on “Next”:

Add Firebase app

Further, we copy Firebase configuration details that connect Vue with Firebase:

Firebase configuration

Here, we will click on “Database”=>”Cloud Firestore” and click on the “Create Database”:

Then, we will have to configure the security rules in test mode:’

Cloud Firestore Security Rules

Next, we need to create a “users” collection. We can make as many collections as we want. The collection is a set of documents that contains specific information or data:

Firebase Collection

 

 

Step 3- Create Vue App With Vue CLI

The next is just to install Vue CLI:

npm install -g @vue/cli

 

Then, we have to verify the Vue-CLI installed version:

vue --version

 

Further, we head over to the newly installed project folder:

cd vue-firebase-crud-app

 

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

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

 

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"
},

 

Then, we run the command to see the Vue app on the browser

npm run serve

 

Step 4- Add Bootstrap 4 In Vue

Here, we will install the Bootstrap in the Vue project by opening the terminal and running the command:

npm install bootstrap

 

Then, we will open the main.js file and import the Bootstrap path inside of it:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import 'bootstrap/dist/css/bootstrap.min.css'
Vue.config.productionTip = false
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

 

Step 5- Creating Vue Components

To manage the data or our CRUD application, we need to create the following files inside the “components” folder:

UserCreate.vue

UserEdit.vue

UserList.vue

 

A regular Vue component seems like this:

<template>
    <div class="row justify-content-center">
        <div class="col-md-6">
            <!-- Content goes here -->
        </div>
    </div>
</template>
<script>
    export default {
        data() {
            return {
            }
        }
    }
</script>
</div>

 

Step 6- Create Vue Router For Firebase CRUD Demo App

In this step, we have to ensure to add Vue router package using mentioned below command:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    name: 'add',
    component: () => import('../components/UserCreate')
  },
  {
    path: '/list',
    name: 'list',
    component: () => import('../components/UserList')
  },
  {
    path: '/edit/:id',
    name: 'edit',
    component: () => import('../components/UserEdit')
  }
]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
export default router

 

Step 7- Add Navigation With Router View

The Bootstrap navigation component creates a beautiful header with nav items. The router-link directive navigates to the specific page and the router-view directive displays the associated component with its router.

Then, we will open the src/App.vue file in which we have to add the following code in it:

<template>
  <div>
    <nav class="navbar navbar-dark bg-dark justify-content-between flex-nowrap flex-row">
      <div class="container">
        <a class="navbar-brand float-left">Firebase Vue CRUD Example</a>
        <ul class="nav navbar-nav flex-row float-right">
          <li class="nav-item">
            <router-link class="nav-link pr-3" to="/">Add User</router-link>
          </li>
          <li class="nav-item">
            <router-link class="nav-link" to="/list">View Users</router-link>
          </li>
        </ul>
      </div>
    </nav>
    <div class="container mt-5">
      <router-view></router-view>
    </div>
  </div>
</template>

 

Step 8- Create Interactive Vue Form With Bootstrap

Here, in this step, we will add the given code inside the components/UserCreate.vue file:

<template>
    <div class="row justify-content-center">
        <div class="col-md-5">
            <h3 class="text-center">Add User</h3>
            <form @submit.prevent="onFormSubmit">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" v-model="user.name" required>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control" v-model="user.email" required>
                </div>
                <div class="form-group">
                    <label>Phone</label>
                    <input type="text" class="form-control" v-model="user.phone" required>
                </div>
                <div class="form-group">
                    <button class="btn btn-primary btn-block">Add User</button>
                </div>
            </form>
        </div>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                user: {
                   name: '',
                   email: '',
                   phone: ''
                }
            }
        },
        methods: {
            onFormSubmit() { 
               alert(JSON.stringify(this.user)) 
            }
        }
    }
</script>

 

Step 9- Install Ans Set Up Firebase In Vue

Here, we will install the Firebase plugin in vue.js that makes the communication between Vue and Cloud Firestore:

npm add firebase@^8.10.0

Now, we have to create a src/firebaseDb.js file after which we will add the given code to establish the real-time database connection in Vue with our Firebase configuration details:

import firebase from 'firebase/app';
import 'firebase/firestore';
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();

 

Step 10- Add Data To Cloud Firestore

Now, we will use the Firestore collection() method to add the data to the cloud firestore database.

<template>
    <div class="row justify-content-center">
        <div class="col-md-5">
            <h3 class="text-center">Add User</h3>
            <form @submit.prevent="onFormSubmit">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" v-model="user.name" required>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control" v-model="user.email" required>
                </div>
                <div class="form-group">
                    <label>Phone</label>
                    <input type="text" class="form-control" v-model="user.phone" required>
                </div>
                <div class="form-group">
                    <button class="btn btn-primary btn-block">Add User</button>
                </div>
            </form>
        </div>
    </div>
</template>
<script>
    import { db } from '../firebaseDb';
    export default {
        data() {
            return {
                user: {
                }
            }
        },
        methods: {
            onFormSubmit(event) {
                event.preventDefault()
                db.collection('users').add(this.user).then(() => {
                    alert("User successfully created!");
                    this.user.name = ''
                    this.user.email = ''
                    this.user.phone = ''
                }).catch((error) => {
                    console.log(error);
                });
            }
        }
    }
</script>

Add Data in Cloud Firestore

 

 

Step 11- Display Data And Delete Data Object From Firestore

The Bootstrap Table component is generally employed for representing the user data that we fetched from the Cloud Firestore using the collection(‘users’).get() method. The router-link directive is taking us to the user details page and we passed the user key/id in the router link.

To delete the user data object from Firestore, we passed the data key to the deleteUser(key) method. The data object can be removed using the delete() method.

Now, we will have to add the given code inside the UserList.vue file:

<template>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="user in Users" :key="user.key">
                        <td>{{ user.name }}</td>
                        <td>{{ user.email }}</td>
                        <td>{{ user.phone }}</td>
                        <td>
                            <router-link :to="{name: 'edit', params: { id: user.key }}" class="btn btn-primary">Edit
                            </router-link>
                            <button @click.prevent="deleteUser(user.key)" class="btn btn-danger">Delete</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>
<script>
    import { db } from '../firebaseDb';
    
    export default {
        data() {
            return {
                Users: []
            }
        },
        created() {
            db.collection('users').onSnapshot((snapshotChange) => {
                this.Users = [];
                snapshotChange.forEach((doc) => {
                    this.Users.push({
                        key: doc.id,
                        name: doc.data().name,
                        email: doc.data().email,
                        phone: doc.data().phone
                    })
                });
            })
        },
        methods: {
            deleteUser(id){
              if (window.confirm("Do you really want to delete?")) {
                db.collection("users").doc(id).delete().then(() => {
                    console.log("Document deleted!");
                })
                .catch((error) => {
                    console.error(error);
                })
              }
            }
        }
    }
</script>
<style>
    .btn-primary {
        margin-right: 12px;
    }
</style>

Display Data & Delete Data Object from Firestore

Step 12- Update Data In Cloud Firestore

The $route.params.id gets the current user’s object id from the URL. Pass it inside the doc() method and access the get() function to render the single document from the Firestore database.

The onUpdateForm() function updates the Firestore Data Object in the data collection. The user redirects to the user’s list view page once successfully updated.

Now, we need to add the following code inside the UserEdit.vue file:

<template>
    <div class="row justify-content-center">
        <div class="col-md-5">
            <h3 class="text-center">Update User</h3>
            <form @submit.prevent="onUpdateForm">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" v-model="user.name" required>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control" v-model="user.email" required>
                </div>
                <div class="form-group">
                    <label>Phone</label>
                    <input type="text" class="form-control" v-model="user.phone" required>
                </div>
                <div class="form-group">
                    <button class="btn btn-primary btn-block">Add User</button>
                </div>
            </form>
        </div>
    </div>
</template>
<script>
    import { db } from '../firebaseDb';
    export default {
        data() {
            return {
                user: {
                }
            }
        },
        created() {
            let dbRef = db.collection('users').doc(this.$route.params.id);
            dbRef.get().then((doc) => {
                this.user = doc.data();
            }).catch((error) => {
                console.log(error)
            })
        },
        methods: {
            onUpdateForm(event) {
                event.preventDefault()
                db.collection('users').doc(this.$route.params.id)
                .update(this.user).then(() => {
                    console.log("User successfully updated!");
                    this.$router.push('/list')
                }).catch((error) => {
                    console.log(error);
                });
            }
        }
    }
</script>

 

Step 13- Deploy Vue App On Firebase Hosting

Deploying Vue on Firebase is quite smooth and easy with Firebase CLI.

 

Conclusion

In this Vue tutorial, we have learned how to create a basic CRUD web application in Vue using the Cloud Firestore real-time database.

 

Thanks

 

Leave a Reply

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