Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reverse the order of an array using v-for and orderBy filter in Vue JS?

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?

like image 278
Soviut Avatar asked Jun 05 '16 03:06

Soviut


3 Answers

Simple and concise solution:

<li v-for="item in items.slice().reverse()">
//do something with item ...
</li>
like image 160
Nima Ajdari Avatar answered Nov 11 '22 03:11

Nima Ajdari


Note: The below works in Vue 1, but in Vue 2 filters are deprecated and you will see: ' Property or method "reverse" is not defined on the instance but referenced during render.' See tdom_93's answer for vue2.

You could create a custom filter to return the items in reversed 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/

like image 32
Pantelis Peslis Avatar answered Nov 11 '22 03:11

Pantelis Peslis


Instead of reversing the order of the elements for creation, I only change the order of the display.

<ol class="reverseorder">
    <li v-for="item in items" track-by="id">

And my CSS

<style>
.reverseorder {
  display: flex;
  flex-direction: column-reverse;
}
</style>

No need to clone the array and reverse it.

like image 36
kirschkern Avatar answered Nov 11 '22 04:11

kirschkern