How to use computed property for v-for in Vue JS


In this short article, we will learn about how to use computed property in v-for in Vue JS.

Sometimes, while working with data in Vue, we use the computed data property to modify, manipulate and display data in an efficient manner to render it on the component.

So how can we use the computed property for v-for data? Let's see with an example.

What is a Computed Property?

A computed property may look just like a method in Vue, but they are not.

In Vue, computed properties allow us to define a property that can be used as any other data property, but we can add some logic to it and return modified or formatted data that already exists.

We write the computed property just like a normal JavaScript function and name of it becomes the name of the property which we can use to render using the curly brackets in Vue template.

Example:

<template>
  <div id="app">
    {{ fullName }}
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      firstName: "Alex",
      lastName: "Johns",
    };
  },
  computed: {
    fullName() {
      return this.firstName + "" + this.lastName;
    },
  },
};
</script>

Here, you can see we have a computed property fullName that returns a value after joining the first and the last name.

Using computed property in V-for in Vue JS

The v-for directive is used to loop through an array in Vue.

Suppose we have an array of objects with first and last names in our data property.

And now we want to create a list of Full Names using the computed property.

Let's see how to do it.

<template>
  <div id="app">
    <ul>
      <li v-for="name in fullName" :key="name">{{ name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      students: [
        {
          firstName: "Alex",
          lastName: "Johns",
        },
        {
          firstName: "Max",
          lastName: "Payne",
        },
        {
          firstName: "John",
          lastName: "Wick",
        },
      ],
    };
  },
  computed: {
    fullName() {
      return this.students.map((item) => {
        return item.firstName + " " + item.lastName;
      });
    },
  },
};
</script>

The fullName is the computed property name. Here we have the map function to loop through the students array to return a new array after joining the first and last name.

Since a computed property can be used like a data property we have used the v-for to loop through the fullName array.

Demo:


💾 Recommended Articles