I need to update a Vue property in a Firebase callback as follow, but it's not working. This code
methods: {
sign_out : function(e) {
this.item_count = 0
}
}
works, but when the property is set in a promise callback:
methods: {
sign_out : function(e) {
firebase.auth().signOut().then(function() {
this.item_count = 0
})
},
How can I set a property's value in this case?
Your this
in your callback is pointing to the wrong object. There are a few ways you can fix this.
Capture this
in a closure.
methods: {
sign_out : function(e) {
var self = this;
self.item_count = 0
firebase.auth().signOut().then(function() {
self.item_count = 0
})
}
Use a fat arrow.
methods: {
sign_out : function(e) {
this.item_count = 0
firebase.auth().signOut().then(() => this.item_count = 0)
}
}
Use bind().
methods: {
sign_out : function(e) {
this.item_count = 0
firebase.auth().signOut().then(function() {
this.item_count = 0
}.bind(this))
}
Fat arrows will not work in all modern browsers yet, so only use them if you are compiling to es5.
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