kayee
kayee

Reputation: 340

how to get nested data in Vue js

I have a view page showing a list of items. When an item is clicked, the current item details will show on the detailed view page. The heading and description for the current item are showing perfectly, however for each item I also have a nested gallery with 3 images and I need to display them too. Here is a jsFiddle

I am using List Rendering in Vue JS

HTML

  <h1 v-if="isActive(0)">Master View</h1>
  <h1 v-if="!isActive(0)">Detailed View</h1>

  <div id="breadcrumb">
    <a v-if="!isActive(0)" @click="setActive(0)">&lt; Back</a>
  </div>

  <main>
    <article>
      <h2>{{items[active].title}}</h2>
      <p>{{items[active].description}}</p>
    </article>

    <ul id="master-ul" v-if="isActive(0)">
      <li v-for="item in items" @click="setActive($index)">
        <img v-bind:src="item.thumbnail" alt="{{item.title}}" />
        <p>{{item.title}}</p>
      </li>
    </ul>

    <ul v-if="!isActive(0)">
      <!-- Need to display the nested images from the current index item -->
      <li v-for="item in items">
        <img v-bind:src="item.gallery.image" />
      </li>
    </ul>
  </main>

</div>

JS

new Vue({
  el: '#app',
  data: {
    active: 0,
    items: [{
      title: 'Default',
      description: 'lorem ipsum default',
      thumbnail: 'http://placehold.it/250x250'

    }, {
      title: 'One',
      description: 'lorem ipsum 1',
      thumbnail: 'http://placehold.it/250x250?text=Item+1+Thumb',
      gallery: {
        image: 'http://placehold.it/250x250?text=Item+1+image+1',
        image: 'http://placehold.it/250x250?text=Item+1+image+2',
        image: 'http://placehold.it/250x250?text=Item+1+image+3'
      }

    }, {
      title: 'Two',
      description: 'lorem ipsum 2',
      thumbnail: 'http://placehold.it/250x250?text=Item+2+Thumb',
      gallery: {
        image: 'http://placehold.it/250x250?text=Item+2+image+1',
        image: 'http://placehold.it/250x250?text=Item+2+image+2',
        image: 'http://placehold.it/250x250?text=Item+2+image+3'
      }

    }]
  },
  methods: {
    isActive: function(i) {
      return this.active === i
    },
    setActive: function(i) {
      return this.active = i
    }
  }
});

Upvotes: 0

Views: 1263

Answers (1)

Linus Borg
Linus Borg

Reputation: 23968

Edited:

use a conmputed property to get the gallery for active item

use another v-for directive on the <img> tag directly to loop through the images in the gallery.

computed: {
  activeImages: function () {
    return this.items[this.active].gallery
  }
}
<ul v-if="!isActive(0)">
 <li>
    <img  v-for="image in activeImages" v-bind:src="image" />
  </li>
</ul>

Upvotes: 1

Related Questions