Home > Enterprise >  vue v-for with conditional logic and not missing iteration
vue v-for with conditional logic and not missing iteration

Time:07-16

I have a list of products and I am looping over them with a v-for loop. For the sake of this example lets say I have 5 products. I want to say that if we are on the third iteration, or index of 2, instead of displaying a product, display a promotional image.

//Expected Output

// there are 5 products

<template v-for="product in collection.products">
  <div >Product 1</div>
  <div >Product 2</div>
  <div ></div>
  <div >Product 3</div>
  <div >Product 4</div>
  <div >Product 5</div>
</template>

My implementation was like this

<template v-for="(product, index) in collection.products">
  <div v-if="index === 2" ></div>
  <div v-else snippet-code-js lang-js prettyprint-override">new Vue({
  el: '#app',
  data: {
    collection: {
        products: ['Product 1', 'Product 2', 'Product 3', 'Product 4', 'Product 5']
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template v-for="(product, index) in collection.products">
  <div v-if="index === 2" >Image</div>
  <div >{{ product }}</div>
</template>
</div>

  • Related