18910140161

JavaScript-无法从vuejs-stack溢出中的setTimeout()更新UI

顺晟科技

2022-10-19 14:09:36

160

从。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不会得到更新。什么可以解决这个问题?


顺晟科技:

确保始终使用箭头函数不阴影关键字:

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

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

<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);
  });
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航