# Realtime chat example code
# Install and connect firebase
To get started with firebase and Vue Native, use this documentation:
Vue native is built using Node.js, so follow the examples available here
# Code
After installing firebase in your project, the following code can be placed in App.vue to simulate a very simple chat application.
Use this code and develop it further to complete lab 2.
<template>
<view class="container">
<text class="text-title-primary">Enter message</text>
<text-input
v-model="messageInput"
:style="{height: 40, width: 100, borderColor: 'gray', borderWidth: 1}"
></text-input>
<button title="Send" @press="onSendMessage"></button>
<text class="text-title-primary">Earlier messages</text>
<text v-for="message in messages" :key="message.key">{{message.text}}</text>
</view>
</template>
<style>
.container {
background-color: white;
align-items: center;
justify-content: center;
flex: 1;
}
.text-title-primary {
color: blue;
margin-top: 10;
margin-bottom: 5;
font-size: 25;
}
</style>
<script>
// Firebase App (the core Firebase SDK) is always required and
// must be listed before other Firebase SDKs
var firebase = require("firebase/app");
// Add the Firebase products that you want to use
require("firebase/database");
var firebaseConfig = { // Follow the linked guide "Installation & Setup in JavaScript" to get these
apiKey: "========= REPLACE WITH YOUR API KEY =========",
authDomain: "========= REPLACE WITH YOUR DOMAIN =========",
databaseURL: "========= REPLACE WITH YOUR URL =========",
projectId: "========= REPLACE WITH YOUR PROJECT ID =========",
storageBucket: "========= REPLACE WITH YOUR URL =========",
messagingSenderId: "========= REPLACE WITH YOUR ID =========",
appId: "========= REPLACE WITH YOUR ID =========",",
measurementId: "========= REPLACE WITH YOUR ID =========",
};
export default {
data() {
return { messageInput: "", messagesRef: "", messages: [] };
},
methods: {
onSendMessage() {
this.messagesRef.push({ text: this.messageInput }, (err) => {
if (err) {
// Alert or show this error to the user if anything goes wrong
console.log({ err });
}
});
},
},
mounted() {
if (!firebase.apps.length) { // Prevent "hot reloading" to cause errors
firebase.initializeApp(firebaseConfig);
}
// "messages" is the name of our data collection
this.messagesRef = firebase.database().ref("messages");
firebase
.database()
.ref("messages") // "messages" is the name of our data collection
.on("value", (snap) => { // "value" is a firebase Query event type, Google "firebase.database.Query" for more
// Empty the all showing messages to avoid duplicates
this.messages = [];
const fbVal = snap.val();
for (const key in fbVal) {
const fbMessage = fbVal[key];
if (fbMessage.text) {
const text = fbMessage.text;
console.log(fbMessage.text);
this.messages.push({ key, text });
}
}
});
},
};
</script>