如何在承诺回调中更新 Vue 应用程序或组件的属性? [英] How can I update a Vue app's or component's property in a promise call back?

查看:19
本文介绍了如何在承诺回调中更新 Vue 应用程序或组件的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

回调中的 this 指向错误的对象.有几种方法可以解决这个问题.

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

  1. 在闭包中捕获this.

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)
      }
    }
    

  • 使用 bind().

  • Use bind().

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

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

    Fat arrows will not work in all modern browsers yet, so only use them if you are compiling to es5.

    这篇关于如何在承诺回调中更新 Vue 应用程序或组件的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆