I have an array that I named "names", which is initially empty
names: []
I'm including elements in this array with the unshift()
function, to always include elements at the beginning of the array and not at the end of it, so I do it like this:
names.unshift("Leonardo")
names.unshift("Victor")
names.unshift("Guilherme")
I'll use v-for to display the array elements on my page as a list:
<ul>
<li v-for="name in names">
{{ name }}
</li>
</ul>
The output will be:
- Guilherme
- Victor
- Leonardo
Now I want to list them with an index, so I do the following:
<ul>
<li v-for="(name, i) in names">
{{ i }}: {{ name }}
</li>
</ul>
and the output will be
- 1: Guilherme
- 2: Victor
- 3: Leonardo
But I want the indexes to be inverted, that is, that I have the following result:
- 3: Guilherme
- 2: Victor
- 1: Leonardo
How do I reverse the order of v-for indexes?
CodePudding user response:
Using a little math to get the reversed index each loop:
<ul>
<li v-for="(name, i) in names">
{{ names.length - i }}: {{ name }}
</li>
</ul>
All credit goes to @kissu, the only person on Stack Overflow with the brains capable of figuring out something this difficult.