[Vuejs]-How to write for loop that start and 0 and show every third index, including index 0 in Vue with v-for?

2๐Ÿ‘

โœ…

You can prepare data first in computed property:

new Vue({
  el: "#app",
  data() {
    return {
      items: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
    }
  },
  computed: {
    everyThird: function() {
      const thirds = []
      for(let i = 0; i < this.items.length; i+=3) {
        thirds.push(this.items[i])
      }
      return thirds;
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <li v-for="(item, i) in everyThird" :key="i">
    {{ item }}
  </li>
</div>

2๐Ÿ‘

If you need to condition looping. You need to do it inside a computed property and return the array. So create an array that contains the elements with the index of multiple 3 in the computed property and then use it in your v-for. In your component you do this

<div>
  <li v-for="(item, index) in elementInThirdPlace" :key="index">
    {{ item }}
  </li></div>

export default {
//your lists of items are here
 data () { 
     return { items: [1,2,3,4,5,6,6] } 
  },
  computed: {
   elementInThirdPlace () {
    return this.items.filter((element, index) => index % 3 == 0 )
   }
 }
}

}

Leave a comment