热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在承诺回拨中更新Vue应用程序或组件的属性?

如何解决《如何在承诺回拨中更新Vue应用程序或组件的属性?》经验,为你挑选了1个好方法。

我需要更新Firebase回调中的Vue属性,如下所示,但它无法正常工作.这段代码

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

工作,但在承诺回调中设置属性时:

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

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



1> Bert..:

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

    this在封闭中捕获.

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

    使用胖箭头.

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

    使用bind().

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

胖箭头在所有现代浏览器中都不起作用,因此只有在编译为es5时才使用它们.


推荐阅读
author-avatar
手机用户2502939381
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有