javascriptarraysvue.jsreverse

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?


Solution

  • 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/