【问题标题】:not able to update the UI from setTimeout() in vuejs [duplicate]无法从 vuejs 中的 setTimeout() 更新 UI [重复]
【发布时间】:2021-11-24 02:03:18
【问题描述】:

我想在从 .vue 文件 (vuejs) 中的 lifeSpanObj 对象获取名称后,在 ui 中每秒更新人名。

<div> {{personName}}</div> // in template using this this(its example not exactly this)



this.lifeSpanObj.forEach((element, i) => {
    setTimeout(function () {
      this.personName = element.name;
      console.log(this.personName);
    }, 1000);
  });

使用上面的示例,我可以在控制台中打印更新的值,但 UI 没有得到更新。有什么办法可以解决这个问题?

【问题讨论】:

    标签: javascript html vue.js settimeout vuejs3


    【解决方案1】:

    确保始终使用箭头功能不影响 this 关键字:

    this.lifeSpanObj.forEach((element, i) => {
      setTimeout(() => {                    // arrow function instead of anonymous function
        this.personName = element.name;     // now this refers to the vue component
        console.log(this.personName);
      }, 1000);
    });
    

    对于原始函数(在 ES5 中),您仍然可以遵循以下方法

    this.lifeSpanObj.forEach((element, i) => {
        var self = this;
        setTimeout(function () {
          self.personName = element.name;
          console.log(self.personName);
        }, 1000);
      });
    

    【讨论】:

    • 这对我有用,谢谢
    猜你喜欢
    • 2017-04-05
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2014-07-10
    • 1970-01-01
    相关资源
    最近更新 更多