Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
Starchand Avatar asked Nov 30 '17 11:11

Starchand


People also ask

Can we return something from forEach?

The forEach method does not return a new array like other iterators such as filter , map and sort . Instead, the method returns undefined itself.

How do I retrieve data from Vue?

For example, before rendering a user profile, you need to fetch the user's data from the server. We can achieve this in two different ways: Fetching After Navigation: perform the navigation first, and fetch data in the incoming component's lifecycle hook. Display a loading state while data is being fetched.


1 Answers

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
});
like image 79
MatWaligora Avatar answered Sep 19 '22 20:09

MatWaligora