Search code examples
javascriptobjectnestedvue.jsvue-resource

how to display nested objects in vue.js


My returned data is an array of objects with a nested object. I'm unable to display the 'events' in a v-for loop in my template as I cannot seem to access that part of the returned data.

The data is returned like this (from Vue DevTools):

list: Object
    user: "name"
    id: "id"
    events: Array[3]
        0: Object
           title: "event 1"
        1: Object
           title: "event 2"
        2: Object
           title: "event 3"

Using Vue-resource (via CDN) how do I get display just the events in my template?

Template:

<template id="events-template">
  <div v-for="events in list">
    @{{events.title}}
  </div>    
</template>

My application:

Vue.component('events', {
template: '#events-template',

data: function() {
    return {
        list: []
    }
},

created: function() {
    this.fetchEventsList();
},

methods: {
    fetchEventsList: function() {
        this.$http.get('events', function(events) {
            this.list = events;
        }).bind(this);
    }
}

});

Solution

  • Ok it seems you try to access the false properties in your loop.

    the list variable does not contain a list/array (object). The array you want to iterate is the events attribute of the list object. so list.events

    Furthermore you want to access the property (title) of the "current" item (event) in the loop. Then you don't have to access to the hole array but rather to the current element. event.title

    Replace your template block:

    <template id="events-template">
        <div v-for="event in list.events">
            @{{event.title}}
        </div>    
    </template>