Build a CRUD Application with Vue.js and Firebase

This post will guide you on how to implement CRUD functionalities using Vue.js and Firestore in Firebase. In this example, I am using employee object with employee id, name, department and position as attributes of employee.

Technologies :

  • Vue.js 3
  • Firebase -: Firestore
  • Material CSS/ Material Icons

First, we need to create the firestore in firebase. Follow the below steps to create a firestore.

  • Go to firebase console using this link and create a project.
  • Register a web app to the project by clicking web app icon
  • Go to Firestore by clicking “Firestore” in the left menu panel of the console.
Menu Panel
  • Click “Start collection” and add a collection Id ( eg: employees)
Collection Creation UI
  • Next add documents to the collection by clicking “Add document”. Click “Auto-ID” to auto generate the document Id and insert the fields with values.
Document Creation UI

Final firestore page will look like below with added documents.

Firestore Page
  • In order to connect the Vue app with firestore, we need to copy the firebase configurations with API key. To get it, click the “project overview” from left menu panel and select “project settings”.
Project Settings
  • Go to “Your apps” section in the project settings page. Under “Firebase SDK snippet”, select config and copy the configurations.
API key

Now, let’s look at the Vue application. Here I have used Vue.js version 3 to implement this application.

Client App Implementation

This app has 4 main components called Dashboard, NewEmployee, UpdateEmployee and ViewEmployee. Dashboard is where we can see all the employees in the database.

All these components are inside view folder and database configurations are inside database folder.

Project Structure

First, you need to install firebase to the project to use firestore inside the app. Install firebase using npm.

          npm install firebase

Then, inside the Vue project, create a file to store copied firebase configs. Here I have created a separate folder called “database” and created a file call db.js inside it to store the configurations.

Import the firebase and firestore inside the db.js file and export the firestore. You can refer the following complete code for db.js.

import firebase from 'firebase'import firestore from 'firebase/firestore'
const firebaseConfig = { apiKey: "xxxxxxxxxxxxxxxxxxxxxx", authDomain: "xxxxxxxxxxxxxxx", projectId: "vxxxxxxxx", storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx", messagingSenderId: "xxxxxxxxxxx", appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", measurementId: "xxxxxxxxx"};// Initialize Firebaseconst firebaseApp = firebase.initializeApp(firebaseConfig);export default firebaseApp.firestore()

In the code, “employees” → our collection which we created inside the firestore and “id” → automatically generated id for each document.

To get all employees from database, you can use the below code from Dashboard component. In this example it is written inside created() hook. So whenever the page loads, employees will be loaded too.

db.collection("employees").orderBy("employee_id").get().then((querySnapshot) => {    querySnapshot.forEach((doc) => {       const data = {           id: doc.id,           employee_id: doc.data().employee_id,           name: doc.data().name,           department: doc.data().department,           position: doc.data().position,       };    this.employees.push(data);   });});

To display employees in a table or a list, iterate them using a v-for loop. In this example, I am using a table to display employees.

<tr v-for="employee in employees" :key="employee.id">   <td>{{ employee.employee_id }}</td>   <td>{{ employee.name }}</td>   <td>{{ employee.department }}</td></tr>

Create a method (eg: saveEmployee()) inside methods block in NewEmployee component to create an employee.

saveEmployee() {   db.collection("employees")   .add({      employee_id: this.employee_id,      name: this.name,      department: this.department,      position: this.position,   })   .then((docRef) => {      this.$router.push("/");    })    .catch((err) => {        console.log(err);     });},

Add a form to the page to get employee details and call saveEmployee method inside the form submit event to create an employee. Bind the values in the form using v-model (supports two-way binding in Vue.js).

@submit.prevent” — is used to prevent page reloading.

<form @submit.prevent="saveEmployee">    <label>Employee Id</label>    <input type="number" v-model="employee_id" required />    <label>Name</label>    <input type="text" v-model="name" required />    <label>Department</label>    <input type="text" v-model="department" required />    <label>Position</label>    <input type="text" v-model="position" required />    <button type="submit" class="btn">Add Employee</button></form>

Create a method (eg: updateEmployee()) inside methods block in UpdateEmployee component to update an employee.

updateEmployee() {   db.collection("employees")   .where("employee_id", "==", this.$route.params.employee_id)   .get()   .then((querySnapshot) => {       querySnapshot.forEach((doc) => {          doc.ref.update({             employee_id: this.employee_id,             name: this.name,             department: this.department,             position: this.position,          })          .then(() => {              this.$router.push({                   name: "ViewEmployee",                   params: { employee_id: this.employee_id },              });          });      });  });},

Just like in create employee, add a form to the update page to update employee details and call updateEmployee method inside the form submit event to update an employee.

<form @submit.prevent="updateEmployee">    <input type="number" v-model="employee_id" required disabled />    <input type="text" v-model="name" required />    <input type="text" v-model="department" required />    <input type="text" v-model="position" required />   <button type="submit" class="btn">Update Employee</button></form>

To delete a particular employee, create a method (eg: deleteEmployee()) inside methods block in a suitable component. I have written this inside ViewEmployee component.

deleteEmployee() {    if (confirm("Are you sure?")) {        db.collection("employees")       .where("employee_id", "==", this.$route.params.employee_id)       .get()       .then((querySnapshot) => {            querySnapshot.forEach((doc) => {                 doc.ref.delete();                 this.$router.push("/");            });        });    }}

Call this deleteEmployee method inside a button to delete an employee.

<button @click="deleteEmployee" class="btn red">Delete</button>

To get an employee by id, create a method (eg: fetchEmployee()) inside methods block in ViewEmployee component.

fetchEmployee() {    db.collection("employees")    .where("employee_id", "==", this.$route.params.employee_id)    .get()    .then((querySnapshot) => {        querySnapshot.forEach((doc) => {            this.employee_id = doc.data().employee_id;            this.name = doc.data().name;            this.department = doc.data().department;            this.position = doc.data().position;        });    });}

To display details of a particular employee, we can use a list.

<ul>    <li><h4>{{ name }}</h4></li>    <li>Employee ID : {{ employee_id }}</li>    <li>Department : {{ department }}</li>    <li>Position : {{ position }}</li></ul>

You can learn more about firebase, firestore queries and Vue.js from below links. Happy Coding !!!😃

References :-

#vue #vue3 #vuejs #firebase #firestore

SE Graduate @ SLIIT 🎓| Cloud Computing Enthusiast | Mobile Dev Enthusiast