我对Vue JS有点困惑以及它是如何工作的。我有以下组件:
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');
}
}
}
});
我的then()
函数中的这一行将数组分配给我的数据对象careerData
。
this.careerData = entries.items
当我尝试运行此for
时:
for (var i = 0, len = this.careerData.length; i < len; i++) {
console.log('Success');
}
它不起作用,因为this.careerData.length
似乎没有数据,它只是一个空数组但是当我尝试在HTML中运行我的组件时,数据完全显示在页。
任何想法我可能会在这里出错,就像我在任何方法中都不能使用this.careerData
一样。知道为什么我无法访问这些数据,即使已经知道我已经在我的fetchData
方法中分配了这些数据了吗?数据设法完全达到前端非常奇怪但是我似乎无法在我的方法中的任何其他位置使用它。
谢谢,尼克
答案 0 :(得分:3)
您正在then
之外运行for循环,因为它是异步运算符,所以当您运行for循环时,该数组仍为空。
将其放在then
函数中:
fetchData: function() {
client.getEntries()
.then(entries => {
this.careerData = entries.items;
for (var i = 0, len = this.careerData.length; i < len; i++) {
console.log('Success');
}
});
}