Sometimes, we want to order objects in v-for with Vue.js.
In this article, we’ll look at how to order objects in v-for with Vue.js.
How to order objects in v-for with Vue.js?
To order objects in v-for with Vue.js, we can create a computed property and then use the computed property with v-for
.
For instance, we write
<template>
<div id="app">
...
<p v-for="user in orderedUsers">{{ user.name }}</p>
...
</div>
</template>
<script>
import { orderBy } from "lodash";
export default {
//...
computed: {
orderedUsers() {
return orderBy(this.users, "name");
},
},
//...
};
</script>
to create the orderedUsers
computed property that returns the this.users
array sorted by the name
property value of each object.
Then we use v-for
to render the objects’ name
property values with v-for
.
Conclusion
To order objects in v-for with Vue.js, we can create a computed property and then use the computed property with v-for
.