How to get the v-for index in Vue.js?

Create a new method:

methods: {
    incrementIndex(key) {
        return key + 1;
    },
},

If the array keys are numbered, starting with zero like items[0], items[1], etc.., you can use the array's keys:

<div v-for="(item, key) in items" :key="key">
    {{ incrementIndex(key) }}
</div>

But if the array's keys are typeof String then you can do:

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

The second version uses the counter from the v-for loop.


Declare an index variable:

<div v-for="(item, index) in items" :key="item.name">

</div>

Demo:

new Vue({
  el: '#app',
  data: {
    items: [{name: 'a'}, {name: 'b'}]
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div v-for="(item, index) in items" :key="item.name">
    {{ index }}: {{ item.name }}
  </div>
</div>

Official docs section - Mapping an Array to Elements with v-for (emphasis mine):

Inside v-for blocks we have full access to parent scope properties. v-for also supports an optional second argument for the index of the current item.

Tags:

Vue.Js