fbpx

Vue.js Firebase Tutorial: Create a CRUD Web Application

Today I’ll show you how to create a CRUD app with Vue and Firebase, So you can be up and running linking Vue and Firebase together. To create our app, we would need some dependencies to install to get us started. Now let start by installing those dependencies right away.

If you want to learn more about Vue.js then check out this Master Vuejs from scratch (incl Vuex, Vue Router) course.

Let name our app “Idea Machine” where you can create, read, update and delete an idea from the app.

 Idea Machine

This is how the app interface looks like and you can view the live app here – https://vue-crud-914bc.web.app/

vue firebase crud

Step 1: Install Vue Using Vue CLI

Open your command prompt or terminal and type below code to install vue using either npm or yarn

npm install -g @vue/cli

Step 2: Install VueFirestore Using Vue CLI

Firstly, create a folder for the project using the following syntax

vue create vue-crud

Navigate into the folder with below command

cd vue-crud

Install VueFirestore using the following command

npm install vue-firestore --save

Import VueFirestore from your main.js file

import Vue from 'vue' 
import App from './App.vue'
import VueFirestore from 'vue-firestore' 

Vue.use(VueFirestore, { 
  key: 'id', // the name of the property. Default is '.key'.     
  enumerable: true // whether it is enumerable or not. Default is true. 
}); 

Vue.config.productionTip = false 

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

Step 3: Create one Component

First, let include Bulma in our application

npm install bulma

Next, create an Idea.vue file inside src>>component folder

<template> 
   <div class="idea"> 
   <div> 
</template> 
<script> 
export default { 
   name: 'Ideas', 
   props: { 
      msg: String 
} 
</script>

Step 4: Add Bulma and some other dependencies

Install Sweetalert2 with below command

npm install sweetalert2

Then, install font-awesome so we can display a nice icon on our project with the following command

npm i --save @fortawesome/fontawesome-svg-core 
npm i --save @fortawesome/free-solid-svg-icons 
npm i --save @fortawesome/vue-fontawesome

Last, install firebase for our project

npm install --save firebase

Update your main.js file with the following code

import Vue from 'vue' 
import App from './App.vue' 
import router from './router' 
import store from './store' 
import { library } from '@fortawesome/fontawesome-svg-core' 
import { faTrashAlt, faEdit, faUser, faBuilding } from '@fortawesome/free-solid-svg-icons' 
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome' import {fb} from './firebase' 
import VueFirestore from 'vue-firestore'
import Swal from 'sweetalert2' 
import 'bulma/css/bulma.css' 
require('firebase/firestore') 
library.add( faTrashAlt, faEdit, faUser, faBuilding, )
Vue.component('font-awesome-icon', FontAwesomeIcon) 

window.Swal = Swal; 
const Toast = Swal.mixin({ 
  toast: true, 
  position: 'top-end', 
  showConfirmButton: false, 
  timer: 3000 }); 
  
window.Toast = Toast; 

Vue.use(fb); 

Vue.use(VueFirestore,{ 
  key: 'id', // the name of the property. Default is '.key'. 
  enumerable: true // whether it is enumerable or not. Default is true. }); 
  
Vue.config.productionTip = false 
  
  new Vue({ 
    router, 
    store, render: 
    h => h(App) 
  }).$mount('#app')

Step 5: Import Ideas component inside Home view

Navigate to src>>views>>Home.vue and update with following code

<template> 
<div class="home"> 
  <Idea msg="Welcome to Your Vue.js App"/> 
  </div> 
</template> 
<script> // @ is an alias to /src 
import Idea from '@/components/Ideas.vue' 
export default { 
  name: 'home', 
  components: { 
    Idea
 } 
} 
</script> 
<style scope lang="scss"> 

</style>

Step 6: Connect to firebase

We will be using firebase to store our idea data using firebase storage. Goto Firebase website to signup.

Create a project, don’t forget to allow read and read when creating a project so you can have permission to store data into firebase.

After that, you will be provided with the below config data to include in your app

var config = { 
  apiKey: "", 
  authDomain: "", 
  databaseURL: "", 
  projectId: "", 
  storageBucket: "", 
  messagingSenderId: ""
 };

Next, create a file “firebase.js” inside the src folder in our app and include the following code.

import {firebase} from '@firebase/app'
import '@firebase/firestore'
// Your web app's Firebase configuration 
var config = { 
  apiKey: "", 
  authDomain: "", 
  databaseURL: "", 
  projectId: "", 
  storageBucket: "", 
  messagingSenderId: ""
}; 

// Initialize Firebase 
const fb = firebase.initializeApp(config)
const db = firebase.firestore()

export {fb, db}

Step 7: Add ideas to the Firebase

Okay, we needed to create two objects to insert an ideas object and created time for the Firebase you created earlier then add that object to the Firebase method to add the items to the Firebase database. Also, we will need to include the firebase config file into our ideas.vue in the component folder.

<script> 
import {fb, db} from '../firebase'; 
export default { 
 name: 'Ideas', 
 props: { 
 msg: String 
}, 
data() { 
 return { 
 deas: [], 
 idea: { 
  name: null, 
  createTime: new Date() }, 
  editMode: 'new' 
 } 
}, 
firestore() { 
 return { 
  ideas: db.collection('ideas'), 
 } 
}, 
methods:{ 
 addIdea() { 
  this.$firestore.ideas.add(this.idea) 
  Toast.fire({ 
    type: 'success', 
    title: 'Idea added successfully' }) 
    this.idea.name = '' 
 } 
} 
</script>

You might also like How to Start Your Programming Blog and Make Money

Step 8: Update Ideas in the Firebase

To update our ideas data in the Firestore, we will need two methods to achieve this. one is to update the ID of data we want to edit into our input field called editIdea then the second would be updateIdea to update any ideas you want to edit on the list of ideas.

editIdea(idea) { 
  this.editMode = "edit"; 
  this.idea = idea; 
}, 
updateIdea() { 
  this.$firestore.ideas.doc(this.idea.id).update(this.idea) 
  this.idea.name = ''; 
  this.editMode = "new"; 
  
  Toast.fire({ 
    type: 'success', 
    title: 'Idea updated successfully' 
  }) 
}

Step 9: Delete Ideas from the Firebase

Now, add the delete code inside Ideas.vue file.

deleteIdea(doc) { 
  Swal.fire({ 
    title: 'Are you sure?', 
    text: "You won't be able to revert this!", 
    type: 'warning', 
    showCancelButton: true, 
    confirmButtonColor: '#3085d6', 
    cancelButtonColor: '#d33', 
    confirmButtonText: 'Yes, delete it!' 
  }).then((result) => { 
    if (result.value) { 
      this.$firestore.ideas.doc(doc.id).delete() 
      Toast.fire({ 
        type: 'success', 
        title: 'Idea deleted successfully' 
      }) 
    } 
  }) 
}

So, our whole Ideas.vue file looks like this

<template>
  <div class="idea">
    <body>
        <div class="container">
          <h1 class="title">Idea Machine</h1>
           <div class="columns">
          <div class="column is-three-fifths is-offset-one-fifth">
            <input class="input" type="text" v-model="idea.name" placeholder="Enter an Idea here">
          </div>
          <div class="column is-offset-one-second">
           <a @click="addIdea" class="button is-link" v-if="editMode == 'new'"> Create </a>
           <a @click="updateIdea" class="button is-primary" v-if="editMode == 'edit'"> Update </a>
          </div>
        </div>
        <div class="columns">
          <div class="column is-three-fifth is-offset-one-fifth">
           <div class="container">          
            <table class="table">
              <tbody>
                <tr v-for="idea in ideas">
                  <td width="86.3%">{{idea.name}}</td>
                  <td width="">
                    <span @click="editIdea(idea)" class="icon has-text-info"><font-awesome-icon icon="edit"></font-awesome-icon></span>
                  </td>
                  <td width="">
                    <span class="icon has-text-info"><font-awesome-icon icon="trash-alt" @click="deleteIdea(idea)"></font-awesome-icon></span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          </div>
        </div>
        </div>
     </body>
  </div>
</template>

<script>
import {fb, db} from '../firebase';
export default {
  name: 'Ideas',
  props: {
    msg: String
  },
  data() {
      return {
        ideas: [],
        idea: {
          name: null,
          createTime: new Date()
        },
        editMode: 'new'
      }
  },
    firestore() {
      return {
        ideas: db.collection('ideas'),
      }
  },
   methods:{
    addIdea() {
          this.$firestore.ideas.add(this.idea)
          Toast.fire({
            type: 'success',
            title: 'Idea added successfully'
          })
          this.idea.name = ''
    },
    deleteIdea(doc) {
        Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
      }).then((result) => {
        if (result.value) {

         this.$firestore.ideas.doc(doc.id).delete()
          
          Toast.fire({
            type: 'success',
            title: 'Idea deleted successfully'
          })

        
        }
      })
    },
    editIdea(idea) {
          this.editMode = "edit";
          this.idea = idea;
    },
    updateIdea() {
          this.$firestore.ideas.doc(this.idea.id).update(this.idea)
          this.idea.name = '';
          this.editMode = "new";
          Toast.fire({
            type: 'success',
            title: 'Idea updated successfully'
          })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.container .title {
   color: white !important;
}
.column {
   padding: 0.20rem !important;
}
.column.is-offset-one-second {
    margin-left: -171px !important;
}
</style>

Finally, our CRUD App with Vue and Firebase Tutorial is over. We have done successfully all the CRUD operations inside Vue Application.

Fork it on Github

 

Adewale Adetona

I'm a FullStack Developer and Digital Marketer. I started this blog to give you the proven strategies and resources you need to accelerate your career as a software developer.

Leave a Reply