Categories
Vue Answers

How to use computed property with v-for in Vue.js?

Spread the love

Sometimes, we want to use computed property with v-for in Vue.js.

In this article, we’ll look at how to use computed property with v-for in Vue.js.

How to use computed property with v-for in Vue.js?

To use computed property with v-for in Vue.js, we can use computed properties like any other reactive properties.

For instance, we write

<template>
  <div>
    <p v-for="name in fullNames" :key="name">
      <span>{{ name }}</span>
    </p>
  </div>
</template>

<script>
//...
export default {
  //...
  computed: {
    fullNames() {
      return this.items.map((item) => {
        return `${item.firstName} ${item.lastName}`;
      });
    },
  },
  //...
};
</script>

to create the fullNames computed property that returns an array.

Then in the template, we render the items in fullNames with v-for.

We set the key prop to a unique value in fullNames.

Conclusion

To use computed property with v-for in Vue.js, we can use computed properties like any other reactive properties.

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 *