Vue uses special properties called āComputed propertiesā to help apps perform best and avoid boring code repetition for developers. In this article you will discover the features behind this incredible properties.
A Computed property is a variable that contains the return value of a function. What differentiates this property from simple JavaScript variables are mainly three factors:
<script setup>
import { reactive, computed } from "vue";
const wizard = reactive({
name: "Harry Potter",
animagus: false,
});
const isAnimagus = computed(() => (wizard.animagus ? "Yes" : "No"));
</script>
<template>
<p>Is {{ wizard.name }} Animagus?</p>
<span>{{ isAnimagus }}</span>
</template>
In the example above we can see how to declare and use a Computed property:
import computed
from Vue library: this is a native API of framework that you must use for declare a Computed Property
computed
takes a callback as a parameter and this callback MUST always have a return statement
last step binding the variable in HTML template
The Computed property is not dissimilar to the method, in fact it is possible use the method approach and obtain the same result. So what is the difference?
Computed properties are cached based on their reactive dependencies, meaning they are only recomputed when dependencies change, while methods are always calculated. For this reason, itās recommended use when itās possible.
By default, Computed properties are getter-only, but itās possible a declare a setter and make Computed a āWritable Computedā.
<script setup>
import { ref, computed } from "vue";
const name = ref("Harry");
const surname = ref("Potter");
const fullName = computed({
get() {
return name.value + " " + surname.value;
},
set(newValue) {
[name.value, surname.value] = newValue.toUpperCase();
},
});
</script>
This approach is not very common, but thereāre some rare cases that it may be necessary.
The returned value from a computed property is derived state. For this reason you donāt need to directly modify the return value, it wouldnāt make sense! Computed Properties are reactive and are calculated whenever their dependencies change.
Computed properties are a very important feature of Vue and allow the development of high-performance applications with lower computational costs. Therefore they are strongly recommended.