Vue.js 3 — Reverse Array Items in v-for Loops

Vue.js provides a solid and feature-rich templating engine. You can use conditionals and loops with JavaScript expressions. You can work with arrays in Vue.js as you would in any other JavaScript code. And JavaScript provides an Array#reverse method that you can use to turn over the item order.

This tutorial shows you how to reverse an array of items in Vue’s v-for loops.

Vue.js 3 Series Overview

Invert the Items Order in Vue.js’ v-for Loops

JavaScript arrays provide a reverse method allowing you to reverse the order of items in place. Reversing the order in place means that you’re mutating the original array. You can avoid mutating the original array by calling the Array#slice method upfront which creates a copy of your original array. Keeping the original array in its “as is” state avoids side effects in your application code.

In Vue.js you can use JavaScript expressions to modify input data. Here’s a sample code inversing the order of items in a v-for loop:

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

const items = ref([1, 2, 3])  
</script>

<template>  
  <h2>Items</h2>

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

The generated output then looks like this:

Items  
- 3
- 2
- 1

Enjoy reversing arrays in Vue.js!

Explore the Library

Find interesting tutorials and solutions for your problems.