Vue.js 3 — Reverse the Index in v-for Loops

Vue.js comes with a solid templating engine. It allows you to use JavaScript expressions in conditionals and loops. That way you can typically calculate everything you need to run complex application code.

This tutorial goes in tandem with our previous tutorial on how to reverse array items in v-for loops. This time, we want to show you how to reverse the index in v-for loops. This is helpful when you want to display items in descending order.

Vue.js 3 Series Overview

Invert the Index in Vue.js’ v-for Loops

Vue.js provides the current item’s index in v-for loops. The index is always matching the item’s position in the related array. In situations where you want to display the highest index first, you need to manually calculate the related value.

Here’s how you can do that: at first, create a variable that contains the number of items in the array you’re going to loop over. Then calculate the “descending” indexes by subtracting the provided index of the v-for loop from your item’s count:

<script setup>  
import { ref } from 'vue'

const items = ref(['a', 'b', 'c'])  
const count = items.length  
</script>

<template>  
  <h2>Items</h2>

  <ul>
    <li v-for="(item, index) in items.slice().reverse()">
      #{{ count - index }} — {{ item }}
    </li>
  </ul>
</template>  

Subtracting the provided index from your item’s count is a way to create descending indexes in v-for loops. Because the first item in the loop has the index 0, the second item in the loop has the index 1, and so on. The last item in your array has the index n - 1 which results in the subtraction of n - (n - 1). And that equation resolves to n - n + 1 resulting in 1.

The generated output then looks like this:

Items  
- #3 — c
- #2 — b
- #1 — a

Enjoy reversing indexes in v-for loops!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.