Search code examples
javascriptvue.jsvuejs2v-for

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


How can i show this code in Vuejs with v-for?

I would like to show data starting with index 0 and then data with every third index up to index 15. Data.length is 16. Like 0,3,6,9,12,15

for( i = 0; i < data.length; i+=3) {}

Solution

  • 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>