5

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.

Ramandeep Singh
  • 179
  • 1
  • 13

2 Answers2

12

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.
  }
}
webnoob
  • 15,747
  • 13
  • 83
  • 165
1

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')
    })
  }
}
Imre_G
  • 2,468
  • 1
  • 17
  • 33
  • Thanks a lot @Imre_G. Though I still can't figure out why it threw "this is undefined", even if it refers to the function itself. – Ramandeep Singh Jan 03 '18 at 15:34