9

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.

0

2 Answers 2

35

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
});
Sign up to request clarification or add additional context in comments.

Comments

10

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

1 Comment

Just to confirm, the second one will work fine. I prefer it personally as it's neater thank having bind(this) everywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.