【发布时间】:2018-12-19 05:07:19
【问题描述】:
我正在使用 Vue.js 和 Firebase 构建一个聊天应用程序。
我是 vue 和 firebase 的新手,并且努力获取用户的电子邮件,以便我可以将其发送到 firebase 以与聊天一起显示。
我试过这个解决方案: How can i get the user in firebase database, to write from a component with 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>
对不起,如果我不清楚。提前致谢!
【问题讨论】:
-
欢迎并感谢所有代码!您收到的错误信息是什么?
-
当代码到达“this.$root.email = user.email;”时,我得到“Typerror: cannot read property of $root of undefined”在 saveEmail 函数中。
-
您是否尝试过设置
this.$root.$data.email,如图here。 -
我收到了同样的信息 :(
标签: javascript firebase vue.js firebase-authentication vue-component