使用vue资源访问API中的嵌套对象(Access nested objects in API using vue resource)

编程入门 行业动态 更新时间:2024-10-18 01:37:25
使用vue资源访问API中的嵌套对象(Access nested objects in API using vue resource)

我刚刚开始使用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: [] },

更多推荐

本文发布于:2023-08-04 04:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410117.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   对象   资源   API   vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!