How can I update a Vue app's or component'

2019-04-10 02:35发布

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?

标签: vue.js vuejs2
2条回答
爷、活的狠高调
2楼-- · 2019-04-10 02:49

One way is to make a reference to this outside of the callback. Use the reference inside the callback to access the this on the intended object.

So try something like:

methods: {
  sign_out : function(e) {
  this.item_count = 0
  _this = this;
  firebase.auth().signOut().then(function() {
       _this.item_count = 0        
    })
 },
查看更多
混吃等死
3楼-- · 2019-04-10 03:01

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.

查看更多
登录 后发表回答