I am using Vue JS to do viewmodel bindings. In my data
object I have an array of items that are sorted in ascending order (oldest to newest) and I'd like to keep it that way for code-based reasons.
var v = new Vue({
el: '#app',
data: {
items: [
{id: 51, message: 'first'},
{id: 265, message: 'second'},
{id: 32, message: 'third'}
],
}
}
However, when I display the array in the template I'd like to reverse the order so that it's descending (newest to oldest). I tried the following:
<ol>
<li v-for="item in items | orderBy -1" track-by="id">
This didn't work since the orderBy
filter seems to require a field name as its first argument.
Is there any way to accomplish this in the template using the v-for
syntax using the orderBy
filter? Or am I going to have to create a custom reverse
filter?
Simple and concise solution:
Update for Vue2
I want to show some ways that you can work with data and not using filters as they are deprecated in Vue2:
inside computed property
Use computed properties in place of filters, which is much better because you can use that data everywhere in component, not only just in template: jsFiddle
inside Vuex getter property
If you're using Vuex, and you store your data in
store.state
object. The best way do some transformation with data stored in state is to do that ingetters
object (for example filtering through a list of items and counting them, reverse order and so on...)and retrieve state from getters in component computed property:
The v-for directive doesn't support iterating backwards, so if you want to order by newest you're going to need to add another field to indicate when the item was added, or change
id
to increment every time an item is added.Then, with
field
being the field indicting the order added:For my use case (which is admittedly, apparently different than the OP...) I wanted to have the indices of the Array in reverse order in the v-for "loop."
My solution was to create a Vue app method
reverseRange(length)
that returns an Array of integers from length-1 to 0. I then used that in myv-for
directive and simply referred to my Array elements asmyArray[index]
every time I needed it.That way, the indices were in reverse order and I was able to then use them to access elements of the Array.
I hope this helps someone who landed on this page with this subtle nuance in their requirements like me.
You could create a custom filter to return the items in reversed order:
Then use it in the
v-for
expression:https://jsfiddle.net/pespantelis/sgsdm6qc/