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.
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.
}
}
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')
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With