Image for post
Image for post
VueJs and Firebase together is incredibly simple.

Building a Chat App; With VueJs + Firebase

As a developer I am constantly learning. One of the latest things I’ve been reading about is firebase, and I am impressed! The possibilities are endless, but real-time data apps have never been easier. So follow along, and you’ll see that you can build a chat app with Vue and Firebase in just minutes. (No knowledge of Node, Sockets, etc required.)

The Essentials

Have Node installed.
Install Vue CLI.

In your terminal wherever you want to create this project, do the following:

vue create firebase-chat

Then you will be presented with some options. Make sure you leave Babel selected, the other options are up to you. For this tutorial, I didn’t select anything else.

cd firebase-chat
npm run serve

And you’re ready to make some things happen!

Do this by going to https://console.firebase.google.com and creating a project.

Then proceed to “database” in the left side nav. And create a “Real Time Database”. Make sure you create the database is “test mode” because it will allow you to read and write to the database.

Finally Add Firebase to Your Web App and you’ll be presented with some JSON. Copy this part:

// Initialize Firebase
var config = {
apiKey: "{your api key}",
authDomain: "your-project.firebaseapp.com",
databaseURL: "https://your-project.firebaseio.com",
projectId: "your-project",
storageBucket: "another-project-418b4.appspot.com",
messagingSenderId: "{your message sender id}"
};
firebase.initializeApp(config);

In your project directory, run the following in your terminal:

npm install firebase

Now create the file “fire.js” in your src/ directory. Add the following, but make sure to use your config data that you got from firebase.

// src/fire.jsimport firebase from 'firebase'var config = {
apiKey: "{your api key}",
authDomain: "your-project.firebaseapp.com",
databaseURL: "your-project.firebaseio.com",
projectId: "your-project",
storageBucket: "your-project.appspot.com",
messagingSenderId: "{your message sender id}"
};
var fire = firebase.initializeApp(config);
export default fire;

Now for the fun part

For the sake of simplicity, let’s just use the App.vue already provided. Clear it out so that you are starting basically from scratch.

<template><div id="app"></div></template><script>export default {
name: 'app',
data() {
return {
username: '',
messages: []
}
},
methods: {

},
mounted(){
},}</script>

Now for this example I am going to have it so that a user types in their username, and then they can chat. So we need to add the username to the data and we need to have a conditional statement in the template to either show a username input or a message input. Lastly we need to make it so that when a user presses “Enter” that the username is saved to the data.

So we add this to the template:

<template>
<div>
<div v-if="!username">
You can't chat without a name. What's your name? <br />
<input type="text" placeholder="Name"
v-on:keyup.enter="updateUsername">
</div>
<div v-else>
From : {{username}}<br />
Message:<br />
<textarea name="" id="" cols="30" rows="10" placeholder="New Message"></textarea>
</div>
</div>
</template>

And we add this to the script:

data() {
return {
username: '',
messages: []
}
},
methods: {
updateUsername(e) {
e.preventDefault();
if(e.target.value){
this.username = e.target.value;
}
},

Now, once the user is “logged in” with a user name, we need to be able to have the user send a message into the chatroom. So:

We add a method:

methods: {
updateUsername(e) {
e.preventDefault();
if(e.target.value){
this.username = e.target.value;
},
sendMessage(e) {
e.preventDefault();
if(e.target.value){
const message = {
username: this.username,
text: e.target.value
}
// To-Do: Push message to firebase e.target.value = ''
}
}
}

And we update the template so that the textarea has this method bound to it.

<textarea name="" id="" cols="30" rows="10" placeholder="New Message" v-on:keyup.enter="sendMessage"></textarea>

Firebase gives us some really helpful tools to access and store data.

We will access our data with a reference (“ref”) and then we can add listeners to this data with a callback, allowing us to update our app accordingly. Each reference can be imagined as a “bucket” of data, we will use “messages” for this app. No configuration needs to be done, just use that reference in your app.

So what we will do is in the mounted() method we will add a reference to “messages” and we will have a listener for “value” which is fired every time the reference is loaded, and when the reference updates. The callback will receive a “snapshot” of the current data that is stored in that reference. This means that we when our app is loaded and every time we push to the reference our app will be updated with the correct information. Isn’t that convenient?

Here is the code:

mounted(){
let vm = this;
const itemsRef = fire.database().ref('messages');
itemsRef.on('value', snapshot => {
let data = snapshot.val();
let messages = [];
Object.keys(data).forEach(key => {
messages.push({
id: key,
username: data[key].username,
text: data[key].text
});
});
vm.messages = messages;
});
}

Note: snapshot is an object where the key is the id of the stored value object.

We iterate over the keys in the snapshot object and push the data to a new messages array. We then set the vm.messages to the new messages array so we are in sync.

Now all we have to do is push to this array when the user sends a message and our data element will be complete.

...
sendMessage(e) {
e.preventDefault();
if(e.target.value){
const message = {
username: this.username,
text: e.target.value
}
//Push message to firebase reference
fire.database().ref('messages').push(message);
e.target.value = ''
}
}

Finally we need to show the messages after they have been sent. So let’s add a quick update to the template to show the messages:

//... template
<hr>
<div class="messages">
<h3>Messages</h3>
<div class="message" v-for="message in messages">
<strong>{{message.username}}</strong>
<p>{{message.text}}</p>
</div>
</div>

And that’s it, you’re all done. Well, it is ugly but you can update the styles on your own time. But now you’ve successfully created a chat app using vue and firebase. I was blown away with how incredibly simple this is to do. I’m falling more and more in love with Vue and now I am going to start implementing firebase in my projects, especially when I want to whip up a quick prototype.

For your convenience, you can look at my code here: https://github.com/andrewhartnett/vue-firebase-chat

Thanks for reading! I hope this has helped you further understand Vue and Firebase.

https://twitter.com/andyhartnett12

Programmer — Writer. @andyhartnett12

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store