Vue Js Firestore CRUD App with Firebase Tutorial

Vue Js Firestore CRUD tutorial; In this guide, we will teach you how to create a Vue js CRUD web application from scratch using the Firebase real-time database’s Cloud Firestore.

Crud operations are the first and foremost steps towards developing a software application; it stands for Create, Read, Update, Delete.

This vue js crud tutorial will help you build a basic single-page application, a project management system where a user can add, view, update and delete data from the client-side with the help of the cloud Firestore. We will give you detail about the nuances concerned with Vue full-stack crud app app development.

Cloud Firestore is a cloud-hosted backend-as-a-service, powered by Firebase real-time-database; it is a NoSQL database that provides a rapid development ecosystem for iOS, Android, and web apps through a native SDK.

With Firestore, you can utterly create sub-collections within documents and create hierarchical data structures that help in scaling even if the size of the database expands.

Vue Js Firestore CRUD Application Example

  • Step 1: Install New Vue Project
  • Step 2: Get Firebase SDK
  • Step 3: Add Firestore in Vue
  • Step 4: Add Routes and Navigation
  • Step 5: Create + Add Document
  • Step 6: Vue Read + Delete Document in Firestore
  • Step 7: Vue Update Document
  • Step 8: Start App in Browser

Install New Vue Project

The vue create command allows you to install the latest vue app on your system.

vue create vue-firestore-crud

We assume Creating UI requires moving heaven and earth, so use the Bootstrap package to lower the time for HTML and CSS development.

npm i bootstrap

Bootstrap CSS has to be added in the src/main.js file.

import 'bootstrap/dist/css/bootstrap.min.css'

After adding bootstrap into Vue, create new component files, move inside the src/components and create following files.

=> CreateComponent.vue

=> UpdateComponent.vue

=> ListComponent.vue

Get Firebase SDK

Next, create a Firebase project to get the Firebase SDK, wherefore visit the Firebase console, signup, and land into the Firebase dashboard.

Now, set project a name and “Create a project”,.

Next, click on the “Web icon” to add Firebase to your app.

Now, you move to add Firebase to your web app screen; provide the app nickname, click on the “Register App”.

Copy “Firebase SDK” details, keep credentials in the text file for later use.

Ultimately, head over to “Firestore Database”, click on Cloud Firestore, set Firestore in “test mode”.

Add Firestore in Vue

Firebase service can be set in vue application using the profound firebase package.

npm i firebase

Previously, we created the Firebase project to obtain the firebase SDK, create a separate src/database.js file.

Like in the given example, import firebase from firebase module, add the firebaseConfig object to create vue and firebase consent.

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 firebaseDatabase = firebaseApp.firestore();

Add Routes and Navigation

Routes are the links or URLs that enables navigation in the app; install vue-router library to create routes in the vue app.

npm install vue-router

Create three routes, the router instance is invoked by VueRouter package, import package similarly inject into the .use() method, update the code in src/main.js file.

import Vue from 'vue';
import App from './App.vue';
import 'bootstrap/dist/css/bootstrap.min.css';


import VueRouter from 'vue-router'
Vue.use(VueRouter)


const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    { 
      path: '/create',
      name: 'create',
      component: () => import('./components/CreateComponent.vue')
    },
    { 
      path: '/collection',
      name: 'collection',
      component: () => import('./components/ListComponent.vue')
    },
    { 
      path: '/update',
      name: 'update',
      component: () => import('./components/UpdateComponent.vue')
    }
  ]
});

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

To initialize the components in the vue view, use the router-view directive; this directive opens the matched route component.

Update code in src/App.vue file.

<template>
  <div>
    <div class="d-flex justify-content-center p-4 mb-3 bg-dark">
      <div>
          <router-link class="nav-link link-light" to="/create">
             Create Project
          </router-link>
      </div>
      <div>
          <router-link class="nav-link link-light" to="/collection">
             Project List
          </router-link>
      </div>
    </div>
    
    <div class="container mt-5">
      <router-view></router-view>
    </div>
  </div>
</template>

Create + Add Document in Firestore Collection

Let’s go after the CREATE feature, add the project management details in the Firestore collection. Use form control to create a basic form, tie the form control with the v-model directive, secondly, import the firebase database.

Access collection method, pass the collection name, inject the object that needs to be stored in the Firestore collection.

Update code in components/CreateComponent.vue file.

<template>
    <div>
        <form @submit.prevent="onSubmit">
            <div class="form-group mb-3">
                <label><strong>Title</strong></label>
                <input type="text" class="form-control" v-model="project.title" required>
            </div>

            <div class="form-group">
                <label><strong>Details</strong></label>
                <textarea class="form-control" rows="4" cols="20" v-model="project.detail" required></textarea>
            </div>

            <div class="d-grid mt-3">
                <button class="btn btn-success btn-block">Create</button>
            </div>
        </form>
    </div>
</template>

<script>
    import { firebaseDatabase } from '../database';

    export default {
        data() {
            return {
               project: { }
            }
        },
        methods: {
            onSubmit(e) {
                e.preventDefault()
                firebaseDatabase.collection('project').add(this.project)
                .then(() => {
                    this.project.title = ""
                    this.project.detail = ""

                    console.log("Project added.");
                }).catch((err) => {
                    console.log(err);
                });
            }
        }
    }
</script>

Get Document Collection + Delete

To render the data objects from firestore collection is not tricky; set an empty array, fetch results and add data into the array, iterate collection with the v-for directive to display the data.

Deleting data object from collection is simple with doc().delete() method, pass the id into the doc() method.

Update code in components/ListComponent.vue.

<template>
    <div>
        <div class="card mb-3" v-for="doc in Projects" :key="doc.key">
            <div class="card-body">
                <h5 class="card-title">{{ doc.title }}</h5>
                <p class="card-text">{{ doc.detail }}</p>

                <router-link :to="{name: 'update', params: { id: doc.key }}" class="card-link btn btn-outline-primary">Edit Project</router-link>
                <button @click.prevent="deleteDoc(doc.key)" class="card-link btn btn-outline-danger">Delete</button>
            </div>
        </div>
    </div>
</template>

<script>
    import { firebaseDatabase } from '../database';
    
    export default {
        data() {
            return {
                Projects: []
            }
        },
        created() {
            firebaseDatabase.collection('project').onSnapshot((snapshotChange) => {
                this.Projects = [];
                snapshotChange.forEach((doc) => {
                    this.Projects.push({
                        key: doc.id,
                        title: doc.data().title,
                        detail: doc.data().detail
                    })
                });
            })
        },
        methods: {
            deleteDoc(id){
                firebaseDatabase.collection("project").doc(id).delete()
                .then(() => {
                    alert("Project removed");
                })
                .catch((err) => {
                    console.error(err);
                })
            }
        }
    }
</script>

Firestore Update Document in Vue

In this final step, we will show you how to add an update feature in the Vue Firebase app wherefore update code in components/UpdateComponent.vue file.

<template>
    <div>
        <form @submit.prevent="onSubmit">
            <div class="form-group mb-3">
                <label><strong>Title</strong></label>
                <input type="text" class="form-control" v-model="project.title" required>
            </div>

            <div class="form-group">
                <label><strong>Details</strong></label>
                <textarea class="form-control" rows="4" cols="20" v-model="project.detail" required></textarea>
            </div>

            <div class="d-grid mt-3">
                <button class="btn btn-danger btn-block">Update</button>
            </div>
        </form>
    </div>
</template>

<script>
    import { firebaseDatabase } from '../database';

    export default {
        data() {
            return {
               project: { }
            }
        },
        created() {
            let routeId = firebaseDatabase.collection('project').doc(this.$route.params.id);
            routeId.get().then((res) => {
                this.project = res.data();
            }).catch((err) => {
                alert(err)
            })
        },        
        methods: {
            onSubmit(e) {
                e.preventDefault()
                firebaseDatabase.collection('project').doc(this.$route.params.id).update(this.project)
                .then(() => {
                    this.$router.push('/collection')
                }).catch((err) => {
                    alert(err);
                });
            }
        }
    }
</script>

Start App in Browser

To start the app on the browser, execute the suggested command.

npm run serve

Open any browser of your choice, add the provided url on the address bar, and hit enter to view the app.

http://localhost:8080

Vue Js Firestore CRUD

Conclusion

Eventually, we have gone through every bit of information we needed to create a basic Vue Firebase CRUD app. However, this is the beginning; ideally, a full-scale app has many more features than this. The primary reason for offering this vue firestore crud example is to proliferate your knowledge. But once you know how things work in vue with firebase, you can add many more features in the Vue Firebase app.