Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  135] [ 3]  / answers: 1 / hits: 86964  / 8 Years ago, sun, june 5, 2016, 12:00:00

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?


More From » arrays

 Answers
20

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/


[#61905] Wednesday, June 1, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shamya

Total Points: 38
Total Questions: 101
Total Answers: 96

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;