Vue.js Firebase Database example – CRUD Operations

vuejs-firebase-database-example-note-app-feature-image

In previous post, we had built a simple Note App that represents Vue.js CRUD example with Vue CLI 3 for building project. This tutorial shows you how to integrate the Vue.js Project with Firebase Database and do CRUD operations.

Related Post: Vue.js CRUD example – a simple Note App

Vue.js Firebase Database example Overview

Goal

Our Vue App can help us write new Notes, then it displays a list of Notes and each Note page (containing title and content) can be modified easily:

vuejs-firebase-database-example-crud-note-app-overview

And, of course, this App interacts with Firebase as backend infrastructure:

vuejs-firebase-database-example-note-app-firebase-database-result

Demo

Project Structure

vuejs-firebase-database-example-crud-note-app-project-structure

We have 3 components:
App.vue holds all of the other components.
NotesList.vue contains all of notes in a List with + Note button.
Note.vue display a single Note in the List that allows us to create new Note or edit current Note.

Technologies

– Vue CLI 3.0.1
– Vue 2.5.17
– Firebase SDK for Javascript 5.4.2

Practice

Setup Vue Project
Install vue-cli

For use Vue CLI anywhere, run command:
npm install -g vue-cli

Init Project

Point cmd to the folder you want to save Project folder, run command:
npm create vue-note-app

You will see 2 options, choose default:

vuejs-crud-example-note-app-project-setup-1

Install Firebase SDK

Run command: npm install firebase
Once the process is done, you can see firebase in package.json:

"dependencies": {
  "firebase": "^5.4.2",
  "vue": "^2.5.17"
},
Setup Firebase Project
Create Project

Go to Firebase Console, login with your Google Account, then click on Add Project.

Enter Project name, select Location:

vuejs-firebase-database-example-note-app-add-firebase-project

Then press CREATE PROJECT.

Config Rules for Firebase Realtime Database

On the left tab, click on Database.
Scroll down, you can see Realtime Database:

vuejs-firebase-database-example-note-app-add-firebase-create-database

Click on Create Database, a window is shown, choose Start in test mode:

vuejs-firebase-database-example-note-app-add-firebase-database-rule.

This action is equivalent to set Database Rules:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}
Child Components

To understand child Components’ code, please read description in the tutorial:
Vue.js CRUD example – a simple Note App

Note Component

components/Note.vue






NotesList Component

components/NotesList.vue






App Component

In this Component, we have to do these things:
– import Firebase, initialize Database, then make reference to the Database.
– import and interact 2 components above (NotesList and Note).
– use Firebase SDK function to do CRUD operations and listen to the Firebase events (create, delete, update).

Import Firebase Database

Go to Firebase Console, choose the Project that we have created before -> Project Overview.
Click on Web App icon:

vuejs-firebase-database-example-note-app-add-firebase-web-app

A Popup will be shown:

vuejs-firebase-database-example-note-app-add-firebase-config-project

Copy the code and paste in App.vue, don’t forget to import, initialize Firebase and create Reference to the Notes Collection:

import firebase from "firebase/app";
import "firebase/database";

var config = {
  apiKey: "xxx",
  authDomain: "ozenero-vue-firebase.firebaseapp.com",
  databaseURL: "https://ozenero-vue-firebase.firebaseio.com",
  projectId: "ozenero-vue-firebase",
  storageBucket: "ozenero-vue-firebase.appspot.com",
  messagingSenderId: "xxx"
};
firebase.initializeApp(config);

const database = firebase.database();
const notesRef = database.ref("notes");
Import Child Components

We define the data() function that returns array of Notes (notes[]) and a number for current Note’s index in the array (index).



export default {
  name: "app",
  components: {
    NotesList,
    Note
  },
  data: () => ({
    notes: [],
    index: 0
  }),
  ...
}

Please remember that we have used $emit in 2 child Components before:
+ Note Component: $emit("app-removeNote") & $emit("app-saveNote")
+ NotesList Component: $emit("app-changeNote", index) & $emit("app-addNote")

Now we have 4 event handlers with @app- prefix that point to corresponding methods inside App component:

export default {
  ...
  methods: {
    addNote() {
      // ...
    },
    saveNote() {
      // ...
    },
    changeNote(index) {
      // ...
    },
    removeNote() {
      // ...
    }
  }
};
Do Firebase Database CRUD Operations

– Create Note using collectionRef.push({data}):

ref = notesRef.push(note);
note.id = ref.key;

– Update Note using nodeRef.update({data}):

notesRef.child(note.id).update({
  title: note.title,
  content: note.content
});

– Delete Note using nodeRef.remove():

notesRef.child(note.id).remove();

– Read list of Notes using collectionRef.once("value", function(snapshot)):

notesRef.once("value", notes => {
  notes.forEach(note => {
    this.notes.push({
      id: note.ref.key,
      title: note.child("title").val(),
      content: note.child("content").val()
    });
  });
});
Listen to the data changes

To listen for changes, use on() methods of firebase.database.Reference to observe events:

// value = snapshot.val() | id = snapshot.key
notesRef.on("child_added", snapshot => {
  console.log("note was added: ", { ...snapshot.val(), id: snapshot.key });
});

notesRef.on("child_removed", snapshot => {
  const deletedNote = this.notes.find(note => note.id === snapshot.key);
  console.log("note was removed: ", deletedNote);

  const index = this.notes.indexOf(deletedNote);
  this.notes.splice(index, 1);
  this.index = this.index === 0 ? 0 : index - 1;
});

notesRef.on("child_changed", snapshot => {
  const updatedNote = this.notes.find(note => note.id === snapshot.key);
  updatedNote.title = snapshot.val().title;
  updatedNote.content = snapshot.val().content;
  console.log("note was updated: ", updatedNote);
});
Full code





Run

– Run Vue.js App with command: npm run serve.
– Open browser with url: http://localhost:8080/.

Source Code

vue-firebase-db-example

0 0 votes
Article Rating
Subscribe
Notify of
guest
69 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments