vuejs-computed-properties

What are Computed Properties and How to Use Them in Vue.js

  • 4 min

In Vue.js, a computed property is a dynamically calculated property based on other reactive properties.

They allow us to calculate derived values reactively. That is, values that depend on other data, and that update automatically when that data changes.

For example

  • Transform data: For example, formatting a date or filtering a list.
  • Calculate derived values: For example, calculating the total of a shopping cart.

Computed properties are reactive, meaning they update automatically when their dependencies change.

Furthermore, they are cached, so they are only recalculated when their dependencies change. This makes them efficient for expensive or repetitive calculations.

The computed function receives a getter (a function that returns the calculated value) and returns a reactive reference.

Let’s see it with a simple example, like calculating the square of a number.

<template>
  <div>
    <p>Number: {{ number }}</p>
    <p>Square: {{ square }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

const number = ref(2);

// Computed property to calculate the square of the number
const square = computed(() => {
  return number.value * number.value;
});

function increment() {
  number.value++;
}
</script>
Copied!

In this example,

  • square is a computed property that depends on number
  • Every time number changes, square is automatically recalculated.

Computed properties with setter

By default, computed properties are read-only. That is, if you try to assign a value to a computed property, Vue.js will throw an error.

However, it is also possible to create computed properties with a setter (if necessary).

Let’s see it with an example, where we calculate the full name, from first name and last name.

<template>
  <div>
    <p>Full name: {{ fullName }}</p>
    <input v-model="firstName" placeholder="First Name" />
    <input v-model="lastName" placeholder="Last Name" />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

const firstName = ref('Juan');
const lastName = ref('Pérez');

// Computed property with getter and setter
const fullName = computed({
  get() {
    return `${firstName.value} ${lastName.value}`;
  },
  set(value) {
    const [newFirstName, newLastName] = value.split(' ');
    firstName.value = newFirstName;
    lastName.value = newLastName;
  },
});
</script>
Copied!

In this example,

  • fullName is a computed property with a getter and a setter
  • The getter returns the full name
  • The setter splits the value into first name and last name

Practical examples