[英]Getting user email from firebase using Vue.js
我正在使用Vue.js和Firebase構建一個聊天應用程序。
我對vue和firebase都是陌生的,我一直在努力獲取用戶電子郵件,因此我可以將其發送到firebase與聊天一起顯示。
我已經嘗試過以下解決方案: 我如何才能使用戶進入Firebase數據庫,以便使用vuejs從組件進行編寫?
但是無法使其正常工作。 我想我真的不知道我在哪里,如何或何時可以訪問root。 原因是當我嘗試this。$ root.something時出現錯誤消息。
這段代碼在我的main.js文件中:
firebase.auth().onAuthStateChanged(function(user) {
if (!app) {
/* eslint-disable no-new */
app = new Vue({
el: '#app',
data: {email: user.email}, //here i want to store the email, which works but I cant access it from other components
template: '<App/>',
components: { App },
router
})
}
});
這是我主要組件中的腳本。 我想在這里成為根。
<script>
import * as firebase from 'firebase'
export default {
name: 'chat',
data: function(){
return {
room: null,
db: null, // assign Firebase SDK later
messageInput:'', // this is for v-model
messages: [],
}
},
mounted() {
this.db = firebase
// access the location and initilize a Firebase reference
this.init()
},
methods: {
init(){
this.room = this.db.database().ref().child('chatroom/1')
this.messageListener()
this.saveEmail();
},
saveEmail(){
//here i tried to save the email using the onAuthStateChanged method
firebase.auth().onAuthStateChanged(function(user) {
this.$root.email = user.email;
});
},
send(messageInput) {
//A data entry.
let data = {
message: messageInput
//here i want to add it to the database
// user: this.$root.email
};
// Get a key for a new message.
let key = this.room.push().key;
this.room.child('messages/' + key).set(data)
// clean the message
this.messageInput = ''
},
messageListener () {
this.room.child('messages').on('child_added', (snapshot) => {
// push the snapshot value into a data attribute
this.messages.push(snapshot.val())
})
},
logout(){
firebase.auth().signOut().then(() => {
this.$root.email = null;
this.$router.replace('login');
})
},
}
}
</script>
這是我的登錄組件中的腳本:
<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('Opppps! ' + err.message);
}
);
},
}
}
</script>
對不起,如果我不清楚。 提前致謝!
onAuthStateChanged
方法的回調綁定到錯誤的此作用域。 您可以使用以下箭頭功能輕松修復此問題。 使用箭頭功能時,它將自動綁定到定義它的上下文。
saveEmail() {
firebase.auth().onAuthStateChanged((user) => {
this.$root.email = user.email;
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.