我刚刚开始使用vue资源(以及一般的ajax),而且我在列出嵌套在我的API中的数组时遇到了麻烦。
如果这是我的样本JSON:
{ "item1" : "data", "item2" : 1234, "item3" : 5678, "item6" : "data", "item7" : [ { "id" : 0, "data2" : "testdata", "data3" : "testdata", },{ "id" : 2, "data2" : "testdata", "data3" : "testdata", },{ "id" : 3, "data2" : "testdata", "data3" : "testdata", } ] }我想通过我的html中的列表传递item7数组,如下所示:
<div id="app"> <ul v-for="item in items"> <li>{{ item.data2 }} {{ item.data3 }}</li> </ul> </div>这是我的js:
window.onload = function() { new Vue({ el: '#app', data: { items: {} }, ready: function () { this.$http.get('/api/items', function(data) { console.log(data); this.items = data.item7[]; }); }, }); };当然这没有返回,我不知道如何通过this.items = data.item7[];循环数组this.items = data.item7[]; 与vue资源。
I'm just starting out with vue resource (and ajax in general) and I'm having trouble listing an array that's nested in my API.
If this is my sample JSON:
{ "item1" : "data", "item2" : 1234, "item3" : 5678, "item6" : "data", "item7" : [ { "id" : 0, "data2" : "testdata", "data3" : "testdata", },{ "id" : 2, "data2" : "testdata", "data3" : "testdata", },{ "id" : 3, "data2" : "testdata", "data3" : "testdata", } ] }I want to pass the item7 array through a list in my html like this:
<div id="app"> <ul v-for="item in items"> <li>{{ item.data2 }} {{ item.data3 }}</li> </ul> </div>Here's my js:
window.onload = function() { new Vue({ el: '#app', data: { items: {} }, ready: function () { this.$http.get('/api/items', function(data) { console.log(data); this.items = data.item7[]; }); }, }); };Naturally this returns nothing, I'm not sure how to loop the array through this.items = data.item7[]; with vue resource.
最满意答案
你只需要编写this.items = data.item7 ,不需要[] 。
您还需要this绑定到该函数。 当您处于来自HTTP请求的回调中时, this指的是其他内容。 所以你可以像这样使用.bind(this) :
this.$http.get('/api/items', function(data) { this.items = data.item7; }.bind(this));最后,如果要将items作为数组,则应将items实例化为数组:
data: { items: [] },You just need to write this.items = data.item7, no need for [].
You also need to bind this to the function. When you're in the callback from the HTTP request, this refers to something else. So you can use .bind(this) like so:
this.$http.get('/api/items', function(data) { this.items = data.item7; }.bind(this));Lastly, you should instantiate items as an array if it is going to be an array:
data: { items: [] },更多推荐
发布评论