[英]List rendering from an external API with VueJS and Axios
I am having a bear of a time getting my VueJs app to render data from an external API. 我花了点时间让我的VueJs应用程序从外部API渲染数据。 I've attempted to search for a similar issue, but everything I've found has been of no help.
我试图搜索类似的问题,但是我发现的所有内容都没有帮助。
I'm using the the USDA's nutrition database . 我正在使用美国农业部的营养数据库 。 When I run the code below, I can see through dev tools that my
getNutrients
function is making a successful call to the database when I click the button, yet my v-for
element won't render any data. 当我运行下面的代码时,通过开发工具可以看到,当我单击按钮时,我的
getNutrients
函数正在成功调用数据库,但是我的v-for
元素不会呈现任何数据。 If I attempt to simply render nutrients
from my data
object, I'm able to render all of the raw JSON, just not when I try to render singular items within the v-for
element. 如果我尝试从
data
对象中简单地渲染nutrients
,那么我就可以渲染所有原始JSON,而当我尝试在v-for
元素中渲染单数项时则不能。
Any help with getting the render to work would be greatly appreciated. 任何帮助渲染工作的帮助将不胜感激。
Thank you in advance 先感谢您
<template>
<div>
<button @click="getNutrients">Click</button>
<ul>
<li v-for="nutrient in nutrients">{{nutrient.nutrient_id}}</li>
</ul>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'home',
data () {
return {
nutrients: {}
}
},
methods: {
getNutrients: function () {
axios.get('https://api.nal.usda.gov/ndb/nutrients/?format=json&api_key=DEMO_KEY&nutrients=205&nutrients=204&nutrients=208&nutrients=269')
.then(response => {this.nutrients = response.data})
}
}
}
</script>
If it helps, I'm using the Vue Webpack template through the Vue-CLI. 如果有帮助,我正在通过Vue-CLI使用Vue Webpack模板。
The API's returning a report
object, which contains an array of foods
, each of which contains an array of nutrients
, so you'd need to loop through the foods
, then through the nutrients
in each food
: API返回一个
report
对象,其中包含一系列foods
,每个foods
都包含一系列nutrients
,因此您需要遍历foods
,然后遍历每种food
的nutrients
:
<ul>
<li v-for="food in foods">
<h2>{{food.name}}</h2>
<ul>
<li v-for="nutrient in food.nutrients">{{nutrient.nutrient_id}}</li>
</ul>
</li>
</ul>
axios.get(url).then(response => {
this.foods = response.data.report.foods
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.