Categories
Vue Answers

How to Reverse the Order of an Array Using v-for in Vue.js?

Spread the love

Sometimes, we want to reverse the order of an array using v-for in Vue.js.

In this article, we’ll look at how to reverse the order of an array using v-for in Vue.js.

Reverse the Order of an Array Using v-for in Vue.js

We can reverse the order of an array using v-for in Vue.js by using the slice and reverse array methods to copy the original array and then reverse it.

For instance, we can write:

<template>
  <div id="app">
    <p v-for="item in items.slice().reverse()" :key="item.id">
      {{ item.message }}
    </p>
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      items: [
        { id: 51, message: "first" },
        { id: 265, message: "second" },
        { id: 32, message: "third" },
      ],
    };
  },
};
</script>

We call item.slice to make a copy of the array and return it.

Then we call reverse to reverse the copied array.

Then we use v-for to render the array items.

Now we see:

third

second

first

as a result.

Conclusion

We can reverse the order of an array using v-for in Vue.js by using the slice and reverse array methods to copy the original array and then reverse it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *