Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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.

share|improve this question
up vote 0 down vote accepted

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: []
},
share|improve this answer
    
Thanks this works! – Mr.Richway Jul 29 at 16:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.