J. Margarine
J. Margarine

Reputation: 417

Using v-for range on attributes in vue.js

I have a long list of images, but want to display only 5 of them

Here's the code I've tried

        <ul>
            <li v-for="index in 5" :key="index">
                <img v-bind:src="image.ImageUrl[index]" />
            </li>
        </ul>

If the use the follow it works, but then it displays all the images

        <ul>
            <li v-for="image in Images">
                <img v-bind:src="image.ImageUrl" />
            </li>
        </ul>

Upvotes: 0

Views: 506

Answers (2)

Bennett Dams
Bennett Dams

Reputation: 7033

Instead of using the index (and bringing logic to your template), you could do this programatically.

Computed properties are perfect for these kind of tasks:

(Replace {{ image }} with your <img ..>)

var app = new Vue({
  el: '#app',
  data: {
    images: [1,2,3,4,5,6,7,8]
  },
  computed: {
    imagesSliced() {
      return this.images.slice(0,5);
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="(image, index) in imagesSliced" :key="index">
    {{ image }}
    <!--  <img v-bind:src="image.ImageUrl" /> -->
    </li>
  </ul>
</div>

Upvotes: 4

akuiper
akuiper

Reputation: 215057

You need to index Images to get the image first, try Images[index].ImageUrl instead of image.ImageUrl[index] where image is not defined inside the first for loop:

<ul>
  <li v-for="index in 5" :key="index">
    <img v-bind:src="Images[index].ImageUrl" />
  </li>
</ul>

Upvotes: 0

Related Questions