orderBy
-
Limited to: directives that expect
Array
values, e.g.v-for
-
Arguments:
{String | Array<String> | Function} ...sortKeys
{String} [order] - default: 1
-
Usage:
Return a sorted version of the source Array. You can pass any number of Strings to sort on keys. You can also pass an array containing the sorting keys or a Function if you want to use your own sorting strategy instead. The optional
order
argument specifies whether the result should be in ascending (order >= 0
) or descending (order < 0
) order.For arrays of primitive values, simply omit
sortKeys
and provide the order, e.g.orderBy 1
. -
Example:
Sort users by name:
<ul> <li v-for="user in users | orderBy 'name'"> {{ user.name }} </li> </ul>
In descending order:
<ul> <li v-for="user in users | orderBy 'name' -1"> {{ user.name }} </li> </ul>
Sort primitive values:
<ul> <li v-for="n in numbers | orderBy true"> {{ n }} </li> </ul>
Dynamic sort order:
<div id="orderby-example"> <button @click="order = order * -1">Reverse Sort Order</button> <ul> <li v-for="user in users | orderBy 'name' order"> {{ user.name }} </li> </ul> </div>
new Vue({ el: '#orderby-example', data: { order: 1, users: [{ name: 'Bruce' }, { name: 'Chuck' }, { name: 'Jackie' }] } })
Sort using two keys:
<ul> <li v-for="user in users | orderBy 'lastName' 'firstName'"> {{ user.lastName }} {{ user.firstName }} </li> </ul>
Sort using a Function:
<div id="orderby-compare-example" class="demo"> <button @click="order = order * -1">Reverse Sort Order</button> <ul> <li v-for="user in users | orderBy ageByTen order"> {{ user.name }} - {{ user.age }} </li> </ul> </div>
new Vue({ el: '#orderby-compare-example', data: { order: 1, users: [ { name: 'Jackie', age: 62 }, { name: 'Chuck', age: 76 }, { name: 'Bruce', age: 61 } ] }, methods: { ageByTen: function (a, b) { return Math.floor(a.age / 10) - Math.floor(b.age / 10) } } })
Please login to continue.