computed() and watch()
Derive values lazily with computed(), react to state changes with watch() and watchEffect(), and control flush timing.
computed() in Composition API
computed(fn) creates a read-only reactive ref that derives its value from other reactive sources. It's cached — the getter only runs when dependencies change.
<script setup>
import { ref, computed } from 'vue';
const items = ref([{ price: 10 }, { price: 20 }, { price: 30 }]);
const tax = ref(0.1);
const subtotal = computed(() => items.value.reduce((s, i) => s + i.price, 0));
const total = computed(() => subtotal.value * (1 + tax.value));
</script>Writable computed()
Pass an object with get and set to create a writable computed. The setter handles updates, typically reflecting the change back to the source ref.
const firstName = ref('Alice');
const lastName = ref('Smith');
const fullName = computed({
get: () => `${firstName.value} ${lastName.value}`,
set: (val: string) => {
[firstName.value, lastName.value] = val.split(' ');
}
});
fullName.value = 'Bob Jones'; // sets both refs