无法从 vuejs 中的 setTimeout() 更新 UI

not able to update the UI from setTimeout() in vuejs

我想在从 .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 不会更新。有什么办法可以解决这个问题?

确保始终使用箭头函数来避免隐藏 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);
  });