【问题标题】:How can I update a Vue app's or component's property in a promise call back?如何在 Promise 回调中更新 Vue 应用程序或组件的属性?
【发布时间】:2017-03-04 00:17:11
【问题描述】:

我需要如下更新 Firebase 回调中的 Vue 属性,但它不起作用。这段代码

methods: {
    sign_out : function(e) {
        this.item_count = 0
    }
}

有效,但在 Promise 回调中设置属性时:

methods: {
  sign_out : function(e) {
  firebase.auth().signOut().then(function() {
      this.item_count = 0
    })
  },

在这种情况下如何设置属性的值?

【问题讨论】:

标签: vue.js vuejs2


【解决方案1】:

您的回调中的this 指向错误的对象。有几种方法可以解决此问题。

  1. 在闭包中捕获this

    methods: {
      sign_out : function(e) {
        var self = this;
        self.item_count = 0
        firebase.auth().signOut().then(function() {
          self.item_count = 0
      })
    }
    
  2. 使用粗箭头。

    methods: {
      sign_out : function(e) {
        this.item_count = 0
        firebase.auth().signOut().then(() => this.item_count = 0)
      }
    }
    
  3. 使用绑定()。

    methods: {
      sign_out : function(e) {
        this.item_count = 0
        firebase.auth().signOut().then(function() {
          this.item_count = 0
        }.bind(this))
    }
    

胖箭头还不能在所有现代浏览器中工作,所以只有在编译到 es5 时才使用它们。

【讨论】:

  • 有时候想给JS打耳光。谢谢你。
【解决方案2】:

一种方法是在回调之外对此进行引用。使用回调中的引用来访问预期对象上的 this。

所以尝试一下:

methods: {
  sign_out : function(e) {
  this.item_count = 0
  _this = this;
  firebase.auth().signOut().then(function() {
       _this.item_count = 0        
    })
 },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2018-04-13
    • 2020-12-19
    • 1970-01-01
    • 2019-02-02
    • 2012-12-06
    • 2019-06-20
    相关资源
    最近更新 更多