简体   繁体   中英

Getting user email from firebase using Vue.js

I'm building a chat app with Vue.js and Firebase.

I'm new to both vue and firebase and struggeling to get the users email so i can send it to firebase to show along with the chat.

I've tried this solution: How can i get the user in firebase database, to write from a component with vuejs?

But can't get it to work. I guess I dont really get where, how or when I can access root. Cause when i tried this.$root.something I get an error message.

This code is in my main.js file:

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 
        })
    }
});

And this is the script in my main component. It's here I want to accses the root.

<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>

And here is 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('Opppps! ' + err.message);
                    }
                );
            },
        }
    }

</script>

Sorry if I'm not being clear. Thanks in advance!

The callback of the onAuthStateChanged method is bind to the wrong this scope. You can easily fix this by using an arrow function like below. When using an arrow function, it will automatically bind to the context it is defined in.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM