Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update a Vue app's or component's property in a promise call back?

Tags:

vue.js

vuejs2

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?

like image 825
AngeloC Avatar asked Mar 04 '17 00:03

AngeloC


1 Answers

Your this in your callback is pointing to the wrong object. There are a few ways you can fix this.

  1. 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
      })
    }
    
  2. Use a fat arrow.

    methods: {
      sign_out : function(e) {
        this.item_count = 0
        firebase.auth().signOut().then(() => this.item_count = 0)
      }
    }
    
  3. 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.

like image 199
Bert Avatar answered Oct 24 '22 03:10

Bert