嵌套循环并保持索引计数在第二个循环中进行

时间:2019-03-20 20:48:44

标签: javascript vue.js

我有两个嵌套循环,我试图在第二个循环中增加一个计数器,因此基本上不会重置计数。

现在:1 2 3 4 1 2 3 4
想要:1 2 3 4 5 7 8

在vanila javascript中,我会有一个变量,但是如何在Vue领域中完成?

EDIt
我希望模板中的计数而不是javascript部分。

new Vue({
  el: "#app",
  data: () => ({
    todos: [],
    activeIndex: -1
  }),
  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}`,
          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 }}
     </li>
    </ul>
  </template>
</div>

3 个答案:

答案 0 :(得分:0)

我不认识Vue,但我认为您需要类似的东西:

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 :(得分:0)

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>

答案 2 :(得分:-1)

在两个循环外定义一个变量,并在第二个循环内递增。

如果您希望该变量是反应性的,请在数据对象上声明该变量

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

请注意,我已将数据声明为返回对象的方法。这样,组件的所有实例都具有自己的数据对象,而不共享一个对象。就您而言,vue实例不是问题,但通常应将其声明为方法而不是对象。

编辑:

您可以将信息保存在每个listItem上,然后从那里打印,而不是在现场进行计算。

您可以将数据用于循环计数,您可以在循环内部对其进行递增

{{loopCounter++}}