How do I reverse the order of an array using v-for and orderBy filter in Vue JS?
Simple and concise solution:
<li v-for="item in items.slice().reverse()">//do something with item ...</li>
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">
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
computed: { reverseItems() { return this.items.slice().reverse(); } }
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 in getters
object (for example filtering through a list of items and counting them, reverse order and so on...)
getters: { reverseItems: state => { return state.items.slice().reverse(); }}
and retrieve state from getters in component computed property:
computed: { showDialogCancelMatch() { return this.$store.state.reverseItems; }}