Categories
Vue Answers

How to order objects in v-for with Vue.js?

Spread the love

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>
export default {
  //...
  computed: {
    orderedUsers() {
      return this.users.sort((a, b) => a.name.localeCompare(b.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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *