Introduction
Computed properties automatically update when their dependencies change. They help keep your UI in sync without extra work.
Computed properties automatically update when their dependencies change. They help keep your UI in sync without extra work.
import { computed } from 'vue'; const myComputed = computed(() => { // return a value based on reactive data });
computed inside the setup() function of your component.computed should return the value you want to track.doubleCount that is always twice the count value.import { ref, computed } from 'vue'; const count = ref(0); const doubleCount = computed(() => count.value * 2);
import { ref, computed } from 'vue'; const firstName = ref('Jane'); const lastName = ref('Doe'); const fullName = computed(() => `${firstName.value} ${lastName.value}`);
This Vue component shows a count and its double. When you click the button, the count increases and the double updates automatically.
<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>Computed properties are cached and only recalculate when their dependencies change.
Always access reactive values inside computed using .value.
Computed properties keep your UI reactive and efficient.
They automatically update when their dependencies change.
Use them inside setup() with the computed function.
computed properties in Vue's Composition API?fullName inside setup()?setup():
const count = ref(2); const double = computed(() => count.value * 2); count.value = 5; console.log(double.value);What will be logged to the console?
setup():
const firstName = ref('John');
const lastName = ref('Doe');
const fullName = computed(() => {
firstName + ' ' + lastName
});statusMessage that returns "Active" if isActive is true, "Inactive" if false, and "Unknown" if isActive is null or undefined. Which code correctly implements this inside setup()?Pass the test and this pattern moves unknown