我目前只是在学习Vue.js,而且我在调用API方面遇到了问题。我从https://swapi.co/api/people/访问了这个公共API,当我访问电影时,我遇到了问题。我已经获得了电影数据,但数据堆积在最后一个数组中,我不知道该怎么做。希望你们能帮助我:D
<script>
import axios from 'axios';
export default {
name: 'home',
data: () => ({
profiles: [],
last_name_v: '',
movies_urls: [],
movies: [],
movie_s: [],
relateds: [],
errors: [],
datas: []
}),
created() {
axios.get('https://swapi.co/api/people/')
.then(response => {
this.profiles = response.data.results.slice(0, 2);
for (var i = 0; i < this.profiles.length; i++) {
var profile_val = this.profiles[i];
var full_name_o = profile_val.name;
var full_name_s = full_name_o.split(' ');
var last_name = full_name_s[full_name_s.length - 1];
profile_val['last_name'] = last_name;
var movie_urls = profile_val.films.slice(0, 4);
console.log(profile_val.films.slice(0, 4));
profile_val['movie_details'] = [];
for (var j = 0; j < movie_urls.length; j++) {
axios.get(movie_urls[j])
.then(response => {
profile_val.movie_details.push(response.data);
})
.catch(e => {
this.errors.push(e);
});
}
this.datas.push(profile_val);
}
})
.catch(e => {
this.errors.push(e);
});
}
}
答案 0 :(得分:0)
一旦你的内部for循环中的所有承诺解决了,你认为profile_val
的价值是什么?
for (var j = 0; j < movie_urls.length; j++) {
axios.get(movie_urls[j])
.then(response => {
profile_val.movie_details.push(response.data);
})
.catch(e => {
this.errors.push(e);
});
}
您可以做的最简单的事情之一是将其移至函数中并在闭包中捕获profile_val
。
function fetchMovieDetails (profile_val, movie_url) {
return axios.get(movie_url)
.then(res => profile_val.movie_details.push(res.data));
}