How to change array order using v-for filter and orderBy in Vue JS?

I use Vue JS to create viewmodel bindings. In my data object, I have an array of elements sorted in ascending order (from oldest to newest), and I would like to save it this 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 show the array in the template, I would like to change the order so that it goes down (from the newest to the oldest). I tried the following:

 <ol> <li v-for="item in items | orderBy -1" track-by="id"> 

This did not work, as it seems to the orderBy filter that the field name is required as the first argument.

Is there a way to do this in the template using v-for syntax using the orderBy filter? Or do I need to create my own reverse filter?

+8
javascript arrays
source share
4 answers

Note. . The following shows that in Vue 1, but in Vue 2, filters are out of date, and you will see: “The property or method“ reverse ”is not defined on the instance, but is mentioned during rendering. 'See tdom_93 answer for vue2.

You can create your own filter to return items in the reverse order:

 Vue.filter('reverse', function(value) { // slice to make a copy of array, then reverse the copy return value.slice().reverse(); }); 

Then use it in the v-for expression:

 <ol> <li v-for="item in items | reverse" track-by="id"> 

https://jsfiddle.net/pespantelis/sgsdm6qc/

+10
source share

Update for Vue2

I want to show some ways to work with data, and not use filters, since they are deprecated in Vue2:

inside computed property

Using computed properties instead of filters, which is much better because you can use this data throughout the component, not just the template: jsFiddle

 computed: { reverseItems() { return this.items.slice().reverse(); } } 

inside the Vuex getter property

If you use Vuex and save your data in the store.state object. The best way to do some transformations with data stored in state is to do it in a getters object (for example, filter through a list of elements and count them, reverse order, etc.)

 getters: { reverseItems: state => { return state.items.slice().reverse(); } } 

and get the state from the getters in the computed component:

 computed: { showDialogCancelMatch() { return this.$store.state.reverseItems; } } 
+9
source share

Simple and concise solution:

 <li v-for="item in items.slice().reverse()"> //do something with item ... </li> 
+6
source share

The v-for directive does not support iteration in the opposite direction, so if you want to order a newer version, you will need to add another field to indicate when the item was added, or change id to increase the item added each time.

Then, when field is a field that indicates the added order:

 <li v-for="item in items | orderBy 'field' -1" track-by="id"> 
0
source share

All Articles