首页 > 解决方案 > 使用 Vue.js 从 firebase 获取用户电子邮件

问题描述

我正在使用 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>

对不起,如果我不清楚。提前致谢!

标签: javascriptfirebasevue.jsfirebase-authenticationvue-component

解决方案


方法的回调onAuthStateChanged绑定到错误的 this 范围。您可以使用如下箭头函数轻松解决此问题。使用箭头函数时,它会自动绑定到定义它的上下文。

saveEmail() {
  firebase.auth().onAuthStateChanged((user) => {
    this.$root.email = user.email;
  })
}

推荐阅读