Integrating Firebase to a VueJS app

Natalia Sulkama
Jun 5 · 6 min read

In my previous article, I wrote about creating a todo -app using VueJS (). We will continue developing the same app further. For now, the app doesn’t store created lists between browser sessions, so we’ll change that by adding a database. We’ll do that using Google’s Firebase. This project uses VueJS version 2.6.10 and Framework7 version 4.2.0.

First, please clone the master branch from this Github repository: .

mkdir todo
cd todo
git clone

After this, go in the folder, install dependencies and we’re good to go.

cd todo-tutorial
npm install
npm start

Our app currently only stores created lists locally, but we don’t want that. In comes Firebase and its realtime database! To quickly get it up and running, visit .

  1. Log in and click Add project.
  2. Name the project whatever — mine is just “todo” — pick your preferred analytics and Firestore location (doesn’t matter for our project) and continue. Data sharing preferences are up to you.
  3. Let Firebase do its thing and when it’s done, in the project overview page, click the Web icon so that we can add Firebase to our web app.
  4. Pick a nickname for our app — just “todo” is fine — and continue.
  5. Copy the generated code and paste it at the end of the body tag in src/index.html.

After that’s done, go back to the Firebase console, and in the left-hand menu, pick Database. Cloud Firestore is great, but we’ll be using the Realtime Database — so just scroll down a bit to where the option is and Create database. For testing purposes, we want to allow all reads and writes, so pick Start in test mode. And we’re ready!


Pushing created lists to the database

Before we can work with the database, we need to include the Realtime Database CDN and a reference to the Firebase database service in our app. Add this in your src/index.html file, below the core Firebase JS SDK:

<script src=”https://www.gstatic.com/firebasejs/6.0.4/firebase-database.js"></script>

Then add this after all the other Firebase code, below firebase.initializeApp(firebaseConfig):

var database = firebase.database();

Now, have a look at src/components/createlist.vue. In the createList function, we’re simply pushing the created lists to an array.

First thing we should do is replace the listid property. For now, it starts at 0 and is simply incremented for each created list. To push data into a Firebase database, we need a unique key for each data object. For this, let’s use a simple function to generate a random 10-letter key:

var ID = function() {
return Math.random().toString(36).substr(2, 10);
};

Now we can use this ID to generate a unique id and key for each of our list objects. Let’s modify the this.createdList object in the createList method to use the ID() function, and push the list to Firebase:

...
createList: function() {
let formData = this.$f7.form.convertToData('#list-form');
if (formData.listname != '' && formData.listname != undefined && this.listItems.length != 0) {
var ID = function() {
return Math.random().toString(36).substr(2, 10);
};
let listKey = ID();
this.createdList = {
name: formData.listname,
items: this.listItems,
id: ID(),
key: listKey
};
// Firebase magic! We're making a reference to the list using a unique ID, then creating the object itself
firebase.database().ref('lists/' + listKey).set({
name: this.createdList.name,
items: this.createdList.items,
id: this.createdList.id,
key: this.createdList.key
});
this.$$('input.input-with-value').forEach(function(input) {
input.value = '';
});
this.listItems = [];
this.listName = '';
this.disabled = 1;
this.$emit('created', this.createdList);
this.$f7.tab.show(tab1, true);
} else {
return false;
}
},
...

That’s all we need! We’re adding the list to the “lists” collection, each with a randomly generated key, and a randomly generated ID. You can have a look on your Firebase console to make sure everything’s working.


Retrieving lists from Firebase

Now that the lists are being added to the database, the next thing we’ll do is retrieve our created lists to display on the homepage and side panel. Our createdList object is being emitted from src/components/createlist.vue to src/components/app.vue on creation. All we need to do is assign it to the todoList data property. In addition, we’ll fetch the stored lists from Firebase using a mounted() hook:

...
mounted() {
let self = this;
// Find data using the "lists" reference
firebase.database().ref(‘lists’).on(‘value’, function(snapshot) {
let returnArr = [];
snapshot.forEach(function(childSnapshot) {
returnArr.push(childSnapshot.val());
// Fill the local data property with Firebase data
self.lists = returnArr;
});
});
},
methods: {
getList: function(list) {
this.todoList = list;
},
...

Now the homepage list display and sidebar list are retrieving data from the database. Everything works, except that checking items and deleting lists still happens only locally.


Checking items

Instead of mutating a local copy of the list to check items, we need to access and update the database list directly to preserve the properties between sessions. In src/components/home.vue, we’ll need to edit the checkTask method like so:

...
checkTask: function(task) {
task.done = !task.done;
// Select specific list, and find the specific item to mutate with its index
firebase.database().ref().child(‘/lists/’ + this.activeList.key + ‘/items/’ + this.activeList.items.indexOf(task))
// Update the “done” property to match local property
.update({ done: task.done });
}
...

Simple as that! You can open up your Firebase console and observe the database value changing each time you check and uncheck tasks in the app.


Deleting lists

Firebase has a very simple function to delete data. We only need to make a reference to the currently active list, check that it exists, and remove it:

deleteList: function(list) {
// Reference to currently active list in database
let selectItem = firebase.database().ref(‘lists/’ + list.key);
// Check that list exists
selectItem.once(‘value’)
.then(() => {
// Call remove() function
selectItem.remove()
.then(function() {
console.log(“Deleted successfully”);
}).catch(function(error) {
console.log(error);
});
})
// Set listSelected to false so that the deleted list doesn’t stay in view
this.listSelected = false;
}

Note: Firebase doesn’t allow creating empty arrays in the database, so we won’t implement the checked arrays to store list items that are checked done. Because of this, in the side panel view of src/components/app.vue, make sure to remove the counter for checked items:

<f7-panel left cover>
<f7-view>
<f7-page>
<f7-navbar title=”Lists”></f7-navbar>
<f7-block v-if=”lists.length === 0">There are no lists.</f7-block>
<div class=”list-length” v-else>
<f7-block v-if=”lists.length === 1" class=”list-length”>
You have <b>{{ lists.length }}</b> list.
</f7-block>
<f7-block v-else-if=”lists.length != 0" class=”list-length”>
You have <b>{{ lists.length }}</b> lists.
</f7-block>
<f7-list no-hairlines-md>
<f7-list-item v-for=”list in lists” @click=”selectList(list)”>
<span style=”width: 65%;”> {{ list.name }} </span>
<!-- REMOVE THE COMMENTED OUT SECTION BELOW -->
<!-- <span :class=”{ ‘all-checked’: list.checked.length === list.items.length }”>
{{ list.checked.length }} / {{ list.items.length }}
</span> -->
<f7-icon f7=”chevron_right” size=”20px”></f7-icon>
</f7-list-item>
</f7-list>
</div>
</f7-page>
</f7-view>
</f7-panel>

That’s it! Firebase has many great features, so feel free to explore them and develop the app further, as this tutorial serves only as a very brief introduction to it.

You can find the finished app code at .

Thank you for reading! 🌸

The Web Tub

Pushing the web current through hybrid mobile and PWA technology. Presented by the Monaca and Onsen UI team.

Natalia Sulkama

Written by

The Web Tub

Pushing the web current through hybrid mobile and PWA technology. Presented by the Monaca and Onsen UI team.