[Vuejs]-Nested loops and to keep the index count going in the second one

1๐Ÿ‘

new Vue({
  el: "#app",
  data: () => ({
    todos: [],
    activeIndex: -1,
    counter: 0,
  }),
  mounted() {
    for (let t of ['first', 'second']) {
      const listObjects = []

      for (let i = 0; i < 10; i++) {
        listObjects.push({
          url: `/${t}/${t}-${i}`,
          name: `${t}-${i}`,
          id: ++this.counter,
          type: t
        })
      }

      this.todos.push({
        type: t,
        listItems: listObjects
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <template v-for="todo of todos">
    <ul>
     <li 
     v-for="(item, i) of todo.listItems" 
     :class="{ 'item--is-active': activeIndex === i }">
     {{ item.name }} id: {{ item.id }}
     </li>
    </ul>
  </template>
</div>

0๐Ÿ‘

I do not know Vue but I think you need something like:

mounted() {
  let i = 0;
  for (let t of ['first', 'second']) {
    const listObjects = []

    for (; i < 10; i++) {
      listObjects.push({
        url: `/${t}/${t}-${i}`,
        name: `${t}-${i}`,
        type: t
      })
    }

    this.todos.push({
      type: t,
      listItems: listObjects
    })
  }
}

-1๐Ÿ‘

Define a variable outside of both loops and increment it inside the second.

If you want tthe variable to be reactive, declare the variable on the data object

data () {
  return {
    loopCounter: 0,
    todos: []
  }
}

Notice that I declared data as a method returning an object. This way all the instances of a component have their own data object and not share one. In your case, a vue instance, is not a problem, but in general you should declare it as a method and not an object.

Edit:

You could save the info on each listItem and print it from there instead of computing it on the spot.

You could use a data for loop count that you increment it inside the loop

{{loopCounter++}}

Leave a comment