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.
The forEach method does not return a new array like other iterators such as filter , map and sort . Instead, the method returns undefined itself.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With