How to use Index Variable In Vue

Vue.js allows accessing the index of the current item directly within the v-for loop by passing and extra parameter to separately specify the index.

Syntax

<ul>
<li v-for="(item, index) in items">
{{ index }} - {{ item }}
</li>
</ul>

Example: The below code implements index variable to use Vue v-for loop in a better way.

JavaScript
<template>
    <div>
        <h2>
            The below list is rendered using the
            <br />v-for loop in a better way.
        </h2>
        <ul>
            <li v-for="(item, index) in items">
                {{ index }} - {{ item }}
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                items: 
                    ['Apple', 'Banana', 'Orange']
            };
        }
    }
</script>

Output:

How to Write Better Vue v-for Loops?

Vue.js is a popular JavaScript framework used for building dynamic web applications. One of its key features is the v-for directive, which allows developers to render a list of items based on an array or an object. Writing efficient and clean v-for loops is crucial for optimizing performance and maintaining readable code.

You can utilize the below approaches to accomplish this task:

Table of Content

  • Using Key Attribute
  • Using Index Variable
  • Using v-for with Computed Properties

Similar Reads

Using Key Attribute

Adding a unique key to each item in the v-for loop improves Vue’s rendering performance and helps in efficiently updating the DOM....

Using Index Variable

Vue.js allows accessing the index of the current item directly within the v-for loop by passing and extra parameter to separately specify the index....

Using v-for with Computed Properties

Sometimes you may need to filter or manipulate the data before rendering it. Computed properties can be used in conjunction with v-for to achieve this....