![Build Vue CRUD App with Cloud Firestore](https://www.positronx.io/wp-content/uploads/2020/04/vue-firebase-crud-9687-01.png)
We will 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.
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
Table of Contents
- Prerequisites
- Setting up Firebase Project
- Create Vue App with Vue CLI
- Add Bootstrap
- Creating Vue Components
- Create Vue Router for Firebase CRUD Demo App
- Add Navigation with Router View
- Create Interactive Vue Form with Bootstrap
- Install and Set up Firebase
- Add Data in Cloud Firestore
- Display Data & Delete Data Object
- Update Data
- Deploy Vue App on Firebase Hosting
- Summary
Vue Js Firebase CRUD Operations Example
We require following tools and frameworks:
- Vue CLI
- Vue
- Firebase
- Bootstrap 5
- 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.
Click on “Continue” to generate the project.
Click on the web icon.
Provide the app nickname and click on “Next”.
Copy Firebase configuration details, It connects Vue with Firebase.
Click on “Database” => “Cloud Firestore” and click on the “Create Database”.
Configure the security rules in test mode.
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.
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
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
Head over to the newly installed project folder.
cd vue-firebase-crud-app
To remove multi-word error warning, add the following code in vue.config.js file.
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false,
})
Node.js Gatsby error – “digital envelope routines::unsupported …”
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 above error for invoking the app, make sure to update the "scripts": []
array in 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"
},
Add Bootstrap in Vue
Open the terminal and run the command to install Bootstrap in Vue.
npm install 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
First, ensure to add vue router package using mentioned below command.
npm add vue-router@^3.1.6
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="mb-3">
<label>Name</label>
<input type="text" class="form-control" v-model="user.name" required>
</div>
<div class="mb-3">
<label>Email</label>
<input type="email" class="form-control" v-model="user.email" required>
</div>
<div class="mb-3">
<label>Phone</label>
<input type="text" class="form-control" v-model="user.phone" required>
</div>
<div class="mb-3">
<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 add firebase@^8.10.0
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 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();
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="mb-3">
<label>Name</label>
<input type="text" class="form-control" v-model="user.name" required>
</div>
<div class="mb-3">
<label>Email</label>
<input type="email" class="form-control" v-model="user.email" required>
</div>
<div class="mb-3">
<label>Phone</label>
<input type="text" class="form-control" v-model="user.phone" required>
</div>
<div class="mb-3">
<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>
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>
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">Update</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>
Run the command to see the vue app on the browser.
npm run serve
App can be seen at:
Local:
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.