Search code examples
jsonvue.jsvue-resource

Access nested objects in API using vue resource


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.


Solution

  • 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: []
    },