0
0
Vueframework~5 mins

Computed in Composition API in Vue

Choose your learning style9 modes available
Introduction

Computed properties automatically update when their dependencies change. They help keep your UI in sync without extra work.

You want to show a value based on other reactive data.
You need to perform simple calculations or formatting for display.
You want to avoid repeating the same logic in your template.
You want to cache a value until its dependencies change.
You want to keep your template clean and easy to read.
Syntax
Vue
import { computed } from 'vue';

const myComputed = computed(() => {
  // return a value based on reactive data
});
Use computed inside the setup() function of your component.
The function inside computed should return the value you want to track.
Examples
This creates a computed property doubleCount that is always twice the count value.
Vue
import { ref, computed } from 'vue';
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
Combines two reactive values into one computed full name.
Vue
import { ref, computed } from 'vue';
const firstName = ref('Jane');
const lastName = ref('Doe');
const fullName = computed(() => `${firstName.value} ${lastName.value}`);
Sample Program

This Vue component shows a count and its double. When you click the button, the count increases and the double updates automatically.

Vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increase</button>
  </div>
</template>

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

const count = ref(0);
const doubleCount = computed(() => count.value * 2);

function increment() {
  count.value++;
}
</script>
OutputSuccess
Important Notes

Computed properties are cached and only recalculate when their dependencies change.

Always access reactive values inside computed using .value.

Summary

Computed properties keep your UI reactive and efficient.

They automatically update when their dependencies change.

Use them inside setup() with the computed function.