Sometimes, we may want to reverse the list ordering without reversing the actual data. We can achieve the same with two different ways in Vue.js. We can update the rendering content in the template code. Or, we can create a computed property containing the reversed list.
First, let’s have a look at how we can update the rendering list in the template:
<script setup>
import { ref } from 'vue'
const myList = ref([
'Apple', 'Banana', 'Mango', 'Pineapple', 'Grapes'
])
</script>
<template>
<div>
<p>
<ul>
<li v-for="(item, i) in myList.slice().reverse()" :key="i">
{{item}}
</li>
</ul>
</p>
</div>
</template>
Code language: HTML, XML (xml)
In the code above, we first slice() the list (to get a new array), and then reverse the returned array using the reverse() method.
Another way is to have a computed property contain the reversed array:
<script setup>
import { ref, computed } from 'vue'
const myList = ref([
'Apple', 'Banana', 'Mango', 'Pineapple', 'Grapes'
])
const reversedList = computed(() => {
return myList.value.slice().reverse()
})
</script>
<template>
<div>
<p>
<ul>
<li v-for="(item, i) in reversedList" :key="i">
{{item}}
</li>
</ul>
</p>
</div>
</template>
Code language: HTML, XML (xml)
You can find a working version of the above code from my repo links below: