Currently, I am in the process of developing a chat application using Vue.js and Firebase.
This project has been quite challenging for me as I am new to both Vue and Firebase. One specific issue I have encountered is trying to retrieve the user's email in order to display it alongside the chat messages on Firebase. Despite attempting various solutions and seeking help from resources like Stack Overflow, I still haven't been able to make it work. The concept of accessing 'root' in my code seems to be causing some confusion, especially when I try methods like this.$root.something.
One example of my code can be found below in the main.js file:
firebase.auth().onAuthStateChanged(function(user) {
if (!app) {
/* eslint-disable no-new */
app = new Vue({
el: '#app',
data: {email: user.email}, //Storing the email here works but I struggle with accessing it from other components
template: '<App/>',
components: { App },
router
})
}
});
In my main component script, I'm aiming to access the root:
<script>
import * as firebase from 'firebase'
export default {
name: 'chat',
data: function(){
return {
room: null,
db: null, //Firebase SDK assignment later
messageInput:'', //For v-model
messages: [],
}
},
mounted() {
this.db = firebase
// Accessing the location and initializing a Firebase reference
this.init()
},
methods: {
init(){
this.room = this.db.database().ref().child('chatroom/1')
this.messageListener()
this.saveEmail();
},
saveEmail(){
//Attempting to save the email using the onAuthStateChanged method
firebase.auth().onAuthStateChanged(function(user) {
this.$root.email = user.email;
});
},
send(messageInput) {
let data = {
message: messageInput
};
let key = this.room.push().key;
this.room.child('messages/' + key).set(data)
this.messageInput = ''
},
messageListener () {
this.room.child('messages').on('child_added', (snapshot) => {
this.messages.push(snapshot.val())
})
},
logout(){
firebase.auth().signOut().then(() => {
this.$root.email = null;
this.$router.replace('login');
})
},
}
}
</script>
The script in my login component:
<script>
import firebase from 'firebase'
export default {
name: 'login',
data: function(){
return {
email: '',
password: '',
}
},
methods: {
signIn: function(){
firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
(user) => {
this.$root.email = user.email;
this.$router.replace('chat');
},
(err) => {
alert('Oops! ' + err.message);
}
);
},
}
}
</script>
If my explanation is unclear, kindly let me know. Thank you for your assistance!