Reputation: 661
I'm getting a little bit confused by Vue JS and how it is working. I have the following component:
Vue.component('careers', {
template: `
<div class="context">
<div v-for="career in careerData">
<h1>{{ career.fields.jobTitle }}</h1>
{{ career.fields.jobDescription }}
</div>
</div>`,
data: function() {
return {
careerData: []
}
},
created: function() {
this.fetchData();
},
methods: {
fetchData: function() {
client.getEntries()
.then(entries => {
this.careerData = entries.items;
});
for (var i = 0, len = this.careerData.length; i < len; i++) {
console.log('Success');
}
}
}
});
This line within my then()
function assigns an Array to my data object careerData
.
this.careerData = entries.items
When I try to run this for
:
for (var i = 0, len = this.careerData.length; i < len; i++) {
console.log('Success');
}
It doesn't work because this.careerData.length
appears to have no data in it, it's just an empty array however when I try running my component within my HTML the data is displayed perfectly on the page.
Any idea where I might be going wrong here, it's as if I can't use this.careerData
in any of my methods. Any idea why I can't access this data even known I have assigned it in my fetchData
method already? It's very strange the data manages to get to the front end perfectly however I can't seem to use it anywhere else within my methods.
Thanks, Nick
Upvotes: 0
Views: 581
Reputation: 17930
You are running the for loop outside the then
and since it's an async operator, the array is still empty when you run the for loop.
put it inside the then
function:
fetchData: function() {
client.getEntries()
.then(entries => {
this.careerData = entries.items;
for (var i = 0, len = this.careerData.length; i < len; i++) {
console.log('Success');
}
});
}
Upvotes: 3