Starchand
Starchand

Reputation: 714

Access vue data object from inside a forEach

I have the below variable in my data:

 data: function () {
    return {
      myVariable: false,
    }
  }

How do I access this variable from with a looping function, like below?

  anArray.forEach(function(item) {
      this.myVariable = true; 
      // do something
  });

I get 'this' is undefinded as its looking in the current loop function, not the vuejs object.

Upvotes: 9

Views: 18133

Answers (2)

Thomas Van der Veen
Thomas Van der Veen

Reputation: 3226

You could bind this to the scope of the function:

anArray.forEach(function(item) {
  this.myVariable = true; 
  // do something
}.bind(this));

Another is by using the arrow notation (I am not 100% sure):

anArray.forEach((item) => {
  this.myVariable = true; 
  // do something
});

Upvotes: 10

MatWaligora
MatWaligora

Reputation: 1217

Use Arrow function so you don't create new scope within forEach loop and keep your this reference of your Vue component.

 anArray.forEach((item) => {
  this.myVariable = true; 
  // do something
});

Upvotes: 35

Related Questions