Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access vuejs 'this ' within firebase 'then' callbacks? [duplicate]

I am trying to add authentication to my vuejs application using firebase. After signing out a user, the user should be sent back to the login page. I have implemented the following code in my HelloWorld.vue file's script:

import firebase from 'firebase'

  export default {
    name: 'HelloWorld',
    data () {
      return {
        msg: 'Welcome to Your Vue.js App'
      }
    },
    methods: {
      logout () {
        firebase.auth().signOut().then(function () {
          this.$router.push('login')
        })
      }
    }
  }

But I get the following error from my vuejs dev tools:

TypeError: this is undefined
[Learn More]
app.js%20line%201954%20%3E%20eval:40:9
logout/<
HelloWorld.vue:37
Pb/e.a</e.g<
auth.js:23
Yb
auth.js:26
Ub
auth.js:26
h.Qb
auth.js:25
Cb
auth.js:19

referring to the this object in the firebase callback

this.$router.push('login')

I need help to figure out why can't I access this in the callback and how can I workaround the problem. Thanks in advance.

like image 549
Ramandeep Singh Avatar asked Jan 03 '18 15:01

Ramandeep Singh


2 Answers

You can use the arrow function to fix this as this isn't scoped to the vue instance when in another function.

methods: {
  logout () {
    firebase.auth().signOut().then(() => { // arrow syntax
      this.$router.push('login')
    })
  }
}

I personally prefer this as it saves another variable declaration.

Another way would be to use bind(this):

methods: {
  logout () {
    firebase.auth().signOut().then(function () { 
      this.$router.push('login')
    }.bind(this)) // bind added.
  }
}
like image 91
webnoob Avatar answered Sep 24 '22 15:09

webnoob


Within a function, 'this' is bound to the function itself and not to the vue instance. A workaround:

methods: {
  logout () {
    const that = this      \\ the ES5 var is also possible
    firebase.auth().signOut().then(function () {
      that.$router.push('login')
    })
  }
}
like image 20
Imre_G Avatar answered Sep 22 '22 15:09

Imre_G