vuejs v-for reverse
Certainly! Here's an example of using v-for
in Vue to reverse the order of a list:
<template>
<div>
<ul>
<li v-for="(item, index) in reversedList" :key="index">{{ item }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: ['Item 1', 'Item 2', 'Item 3', 'Item 4'],
};
},
computed: {
reversedList() {
return this.list.slice().reverse();
},
},
};
</script>
Explanation:
- The list
array contains the items you want to display.
- In the template section, v-for
iterates through the reversedList
.
- reversedList
is a computed property that returns a reversed copy of the list
array using slice()
and reverse()
methods to maintain immutability.
- The :key
binding ensures proper Vue rendering by using the index
as a unique identifier for each item in the list.