Vue 13: Computed Properties Deep Dive
easy⏱ 5 mincoursevue
A computed with get and set
Pass computed({ get, set }) instead of a plain function to make a two-way computed: reading it runs get(), and assigning computed.value = x runs set(x). This is the classic pattern for things like a formatted-currency input that displays a string but writes back a number, or — as in this lesson — a combined fullName field over two separate firstName/lastName refs.
import { ref, computed } from 'vue';
const first = ref('Ada');
const last = ref('Lovelace');
const full = computed({
get: () => first.value + ' ' + last.value,
set: (val) => {
const parts = val.split(' ');
first.value = parts[0];
last.value = parts[1] || '';
},
});
full.value = 'Grace Hopper'; // runs set() -> updates first & last
Computed values are cached
A computed's get only reruns when one of its tracked dependencies changes — reading .value multiple times in a row between changes returns the cached result without recomputing. A plain function called from the template, by contrast, reruns on every single re-render. This is the main reason to reach for computed over a method whenever you're deriving a value from reactive state.
Prove the cache, then break the two-way binding
Click read twice and confirm the get() call count only goes up by one, not two — that's the cache. Then click set fullName and confirm both firstName and lastName refs updated behind the scenes.