【发布时间】:2020-02-03 13:32:15
【问题描述】:
我使用 Vue.js + Axios 从第三方 API 查询数据。数据很好地返回,但它有一些令人困惑的结构(嵌套数组)。
不知何故,Vue 无法正常工作,我没有看到前端呈现的任何数据。
重要提示:
在我运行代码后,Vue 向前端添加了 20 个 html div(与包含元素的数量相匹配,但它不显示相应的数据(见下图))。
这里可能有什么问题?
Javascript 部分:
var app = new Vue({
el: '#app_name',
data: {
info: []
},
mounted() {
axios
.get("https://cors-anywhere.herokuapp.com/https://www.api-football.com/demo/api/v2/leagueTable/" + league_id)
.then(response => {
this.info = response.data.api.standings[0];
console.log(response.data.api.standings[0]);
});
}
HTML 部分:
<div class="table" id="app_name">
<div><p>Team</p></div>
<div v-for="Rank in info">
<p>{{ Rank }}</p>
</div>
这是 JSON 返回,注意嵌套数组:
{
"api": {
"results": 1,
"standings": [
[
{
"rank": 1,
"team_id": 85,
"teamName": "Paris Saint Germain",
"logo": "https://media.api-football.com/teams/85.png",
"group": "Ligue 1",
"forme": "DLWLL",
"description": "Promotion - Champions League (Group Stage)",
"all": {
"matchsPlayed": 35,
"win": 27,
"draw": 4,
"lose": 4,
"goalsFor": 98,
"goalsAgainst": 31
},
"home": {
"matchsPlayed": 18,
"win": 16,
"draw": 2,
"lose": 0,
"goalsFor": 59,
"goalsAgainst": 10
},
"away": {
"matchsPlayed": 17,
"win": 11,
"draw": 2,
"lose": 4,
"goalsFor": 39,
"goalsAgainst": 21
},
"goalsDiff": 67,
"points": 85,
"lastUpdate": "2019-05-04"
},
{...}
]
]
}
}
Javascript 执行前:
Javascript 执行后:
更新
我尝试了这个修改(来源:https://github.com/axios/axios/issues/738),但我仍然没有渲染任何数据
var app = new Vue({
el: '#app_name',
data: {
info: []
},
mounted() {
axios.interceptors.request.use(config => {
config.paramsSerializer = params => {
// Qs is already included in the Axios package
return Qs.stringify(params, {
arrayFormat: "brackets",
encode: false
});
};
return config;
});
axios
.get("https://cors-anywhere.herokuapp.com/https://www.api-football.com/demo/api/v2/leagueTable/" + league_id)
.then(response => {
this.info = response.data.api.standings;
console.log(response.data.api.standings);
});
}
【问题讨论】:
-
不要在mounted()中调用api,在created()中尝试,甚至在此之前,确保mount前有所有数据。
-
试过了,没变。那么在mounted中插入什么?
-
@Phanti
created钩子是获取数据的理想选择。尝试将v-if放在迭代的<div v-for="(Rank, index) in info" :key="index">上。这个{{Rank}}也是整个对象,想从中访问什么?。 -
我有 11 个要获取的对象,但如果有一个可以使用,我可以计算出其他的。我尝试了您的代码,但仍然得到没有任何渲染数据的空 html 容器。 Vue 只是创建容器。问题是如何引用数组中的元素,因为它以某种方式嵌套..
-
该 API 可能需要很长时间才能完成,而此时 created() 和mounted() 已经运行。使
v-if="info.length",如果为0,则显示加载,如果有长度,则显示循环。另外,尽量不要赋值给数组,如果你给数组赋值,Vue 无法检测到数组的变化。使用推或其他东西。 vuejs.org/v2/guide/list.html#Array-Change-Detection
标签: javascript vue.js