2 回答
TA贡献1812条经验 获得超5个赞
您需要两个循环来显示交通拥堵情况,一个通过roadEntries数组,一个内部循环通过trafficJams每条道路的数组。
要了解 vue.js 中的循环用法,我鼓励您阅读v-for 文档。
一个计算的属性也是在这种情况下,会非常方便过滤所有可能没有遇到任何堵车的道路。
new Vue({
el: '#app',
data() {
return {
datum: '',
roadEntries: [],
}
},
computed: {
roadEntriesWithTrafficJams() {
return this.roadEntries.filter(roadEntry => roadEntry.events != null && roadEntry.events.trafficJams != null && roadEntry.events.trafficJams.length > 0);
}
},
mounted() {
const api = 'https://www.anwb.nl/feeds/gethf';
// Make a request for a user with a given ID
axios.get(api).then((response) => {
this.datum = response.data.dateTime;
this.roadEntries = response.data.roadEntries;
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<h3>
Date time : {{ datum }}
</h3>
<div v-for="roadEntry in roadEntriesWithTrafficJams">
<h4>
{{ roadEntry.road }}
</h4>
<div v-for="trafficJam in roadEntry.events.trafficJams">
{{ trafficJam.from }} - {{ trafficJam.to }}
</div>
</div>
</div>
TA贡献1831条经验 获得超4个赞
我的答案不是完整的 Vue 解决方案,但我专注于如何从 API 响应中提取所需的数据到一个数组(然后可以由 v-for 循环):
// consider these variables in your Vue data()
let date = '';
const trafficJams = [];
axios.get('https://www.anwb.nl/feeds/gethf')
.then((resp) => {
date = resp.data.dateTime;
const roadEntries = resp.data.roadEntries;
// loop through all roadEntries
roadEntries.forEach(entry => {
// extract the trafficJams array to a variable for easier reading
const jams = entry.events.trafficJams;
// if there are jams on the given road (entry):
if (jams.length > 0) {
// loop through all traffic jam and push the needed data to your variable
jams.forEach(jam => {
trafficJams.push({
road: entry.road,
from: jam.from,
to: jam.to
});
});
}
});
// and there you have "road", "from" and "to" data for all traffic jams
console.log(trafficJams);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
添加回答
举报