Vue.js 2|3 Firebase: Build Vue CRUD App with Cloud Firestore

Last updated on by Digamber
This is a step by step tutorial that explains how to build a Vue.js 2|3 CRUD web application using Firebase database.

Build Vue CRUD App with Cloud Firestore

We are going to create a basic customer records management system, in which a user can perform CRUD operations and store the data into the Cloud Firestore.

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

It updates the data in real-time even it updates the data on all the connected devices as soon as the information updates on the cloud Firestore, and the beautiful thing is you don’t have to write the APIs.

Here are some of the Firebase Features:

  • Push notifications
  • Ready-made API
  • Realtime data update
  • Enhanced security
  • Cloud storage
  • Easy A/B testing
  • Analytics monitoring
  • Easy server management
  • Offline access to WEB SDK
  • Hosting and cloud storage
  • Authentication with Email & password, Google, Facebook, & Github

If you are new to vue development and want to build Vue CRUD application with Node and Express.js then you must check out our previously written article: MEVN Stack Tutorial – Build Full-Stack Vue.js CRUD App

Vue.js Firebase CRUD Web App Example

We require following tools and frameworks:

  • Vue CLI v4.3.1
  • Vue 2.6.11
  • Firebase
  • Bootstrap 4
  • IDE or Code Editor

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.

Read more: Integrate Firebase in Vue with VueFire

Place the following url console.firebase.google.com on the browser’s address bar and press enter. It will take you to the Firebase official website.

Click “Create a project”.

Click on “Add project”, we don’t need to enable analytics for this demo.

Setting up Firebase Project

Click on “Continue” to generate the project.

project name

Click on the web icon.

Firebase web icon

Provide the app nickname and click on “Next”.

Add Firebase app

Copy Firebase configuration details, It connects Vue with Firebase.

Firebase configuration

Click on “Database” => “Cloud Firestore” and click on the “Create Database”.

Configure the security rules in test mode.

Cloud Firestore Security Rules

Next, create a “users” collection. You can make as many collection as you want. The collection is a set of document that contains specific information or data.

Firebase Collection

Create Vue App with Vue CLI

The Vue CLI offers the conventional tooling for rapid Vue.js development. Run the command in the terminal to install Vue CLI.

npm install -g @vue/cli

# or 

yarn global add @vue/cli

Verify the vue-cli installed version:

vue --version

Create a brand new Vue.js project from scratch using the below command.

vue create vue-firebase-crud-app

Answer the following question asked by Vue CLI:

# ? Please pick a preset: Manually select features
# ? Check the features needed for your project: Babel, Router, CSS Pre-processors, Linter
# ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
# ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass)
# ? Pick a linter / formatter config: Basic
# ? Pick additional lint features: Lint on save
# ? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
# ? Save this as a preset for future projects? (y/N) No

Head over to the newly installed project folder.

cd vue-firebase-crud-app

Run the command to see the vue app on the browser.

npm run serve

App can be seen at:

Local: http://localhost:8080/
Network: http://192.168.0.103:8080/

Add Bootstrap 4 in Vue

Open the terminal and run the command to install Bootstrap in Vue.

npm install bootstrap

# or

yarn add bootstrap

Add the Import path in the main.js file. It will let us use the Bootstrap components throughout the vue application.

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')

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>

Create Vue Router for Firebase CRUD Demo App

Go to router/index.js file and replace with the given code. We are adding the particular url path with its associated component.

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

Add Navigation with Router View

The Bootstrap navigation component creates the 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.

Open src/App.vue file, 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>

Create Interactive Vue Form with Bootstrap

Add the following code inside components/UserCreate.vue file.

To understand forms in Vue, please check out the following tutorial: Form Validation in Vue with Vuelidate

<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>

Install and Set up Firebase in Vue

Install Firebase plugin in vue.js, it makes the communication between Vue and Cloud Firestore.

npm install firebase

Create a src/firebaseDb.js file then add the following code to establish the real-time database connection in vue with your Firebase configurations details.

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();

Add Data in Cloud Firestore

We will use the firestore collection() method to add the Data in the Cloud Firestore Database.

Add the following code inside the 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>
    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

Display Data & Delete Data Object from Firestore

The Bootstrap Table components is famously 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.

Add the following 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

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.

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>

Deploy Vue App on Firebase Hosting

Deploying Vue on Firebase is easy with Firebase CLI, we have written a detailed tutorial on

Deploying a Vue.js Applicaion to Firebase Hosting in Less Than 5 Minutes

Summary

So thats it for now, we have finished the Vue.js and Firebase tutorial. I hope this tutorial will give you the basic idea of how we can create a basic CRUD web application in Vue using the Cloud Firestore real-time database.

You can download the complete source code on GitHub.