因此,我设置了一个简单的API,以便可以随意使用Vue.js,但我不太了解axios的工作原理。它从API返回数据,但我不确定如何处理数据。
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('http://localhost:8000/foods/')
.then(response => {
console.log(response.data);
this.info = response.data
})
}
})
响应看起来像这样
{"count":4,"next":null,"previous":null,"results":[{"url":"http://localhost:8000/foods/1/","food_name":"Pizza","country_of_origin":"Italy"},{"url":"http://localhost:8000/foods/2/","food_name":"Curry","country_of_origin":"India"},{"url":"http://localhost:8000/foods/3/","food_name":"Stew","country_of_origin":"United Kingdom"},{"url":"http://localhost:8000/foods/4/","food_name":"Bratwurst","country_of_origin":"Germany"}]}
我尝试过this.info = response.data.results[0].food_name
,但这似乎不正确。如何输出响应的result
部分中的所有内容?还是我完全错过了什么?
答案 0 :(得分:2)
所以首先,您知道响应错误
因为您的node_modules/drupal-node.js/slack_chat_extension
如下:
response.data
我认为,如果您使用{
"count": 4,
"next": null,
"previous": null,
"results": [{
"url": "http://localhost:8000/foods/1/",
"food_name": "Pizza",
"country_of_origin": "Italy"
}, {
"url": "http://localhost:8000/foods/2/",
"food_name": "Curry",
"country_of_origin": "India"
}, {
"url": "http://localhost:8000/foods/3/",
"food_name": "Stew",
"country_of_origin": "United Kingdom"
}, {
"url": "http://localhost:8000/foods/4/",
"food_name": "Bratwurst",
"country_of_origin": "Germany"
}]
}
,您将会得到
this.info = response.data.results
如果使用[{
"url": "http://localhost:8000/foods/1/",
"food_name": "Pizza",
"country_of_origin": "Italy"
}, {
"url": "http://localhost:8000/foods/2/",
"food_name": "Curry",
"country_of_origin": "India"
}, {
"url": "http://localhost:8000/foods/3/",
"food_name": "Stew",
"country_of_origin": "United Kingdom"
}, {
"url": "http://localhost:8000/foods/4/",
"food_name": "Bratwurst",
"country_of_origin": "Germany"
}]
(n =数组len中的任何数字),例如this.info = response.data.results[n]
,您将得到
this.info = response.data.results[0]
我建议每当您不知道该对象时,对其进行打印并尝试逐一遍历它的元素
答案 1 :(得分:0)
弄清楚了。最好使用response.data.results
new Vue({
el: '#app',
data () {
return {
info: []
}
},
mounted () {
axios
.get('http://localhost:8000/foods/')
.then(response => {
this.info = response.data.results
})
}
})