如何在组件方法中通过ajax循环数据集?问题是,当我尝试调用一个方法来执行组件的mount()时,数据还没有。如何告诉我的vue组件等待ajax数据到达以执行该功能?
Vue.component('sidebar', {
props: ['people'],
template: `
<div id="sidebarContain" v-if="this.people">
<div v-for="person in people" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id">
{{person.first_name + ' ' + person.last_name}}
</div>
</div>
`,
methods: {
isCheckedIn(person) {
return person.reg_scan == null ? true : false;
},
displayName() { //this is the function I want to run when ajax data is done and passed from parent to child
for (var i = 0; i < this.people.length; i++) {
console.log(this.people[i]);
}
}
},
mounted() {
this.displayName();
}
});
var app = new Vue({
el: '#main',
data: {
people: []
},
methods: {
loadPeople() {
$.ajax({
method: 'POST',
dataType: 'json',
url: base_url + 'users/getParticipants/' + event_id
}).done(data => {
this.people = data;
});
},
setRefresh() {
setInterval(() => {
console.log("Getting People");
this.loadPeople();
}, 10000);
}
},
mounted() {
this.loadPeople();
this.setRefresh();
}
});
<div id="app">
<sidebar :people="people"></sidebar>
</div>
答案 0 :(得分:0)
您可以在人员阵列上设置观察者并在观察者上调用displayName函数。每当人员阵列中的数据发生变化时,观察者就会运行,因此当ajax请求从API返回数据时,它将运行。另一个选择是在回调上立即运行循环。