0

i want to update name of person after every second in ui after feching name from lifeSpanObj object in .vue file (vuejs).

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

using the above example i am able to print updated values in console but UI does not get updated. what could fix for this?

Tarun Jain
  • 152
  • 1
  • 14

1 Answers1

2

Make sure always use arrow function to not shadow this keyword:

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

for primitive function (in ES5) you can still follow the below approach

this.lifeSpanObj.forEach((element, i) => {
    var self = this;
    setTimeout(function () {
      self.personName = element.name;
      console.log(self.personName);
    }, 1000);
  });
Psidom
  • 195,464
  • 25
  • 298
  • 322