computed() membuat derived state — nilai yang dihitung dari data lain dan otomatis ter-cache.
const firstName = ref("Budi")
const lastName = ref("Santoso")
const fullName = computed(() => {
return firstName.value + " " + lastName.value
})
---template---
<p>{{ fullName }}</p>
Computed vs Method
- Computed: Di-cache, hanya dihitung ulang saat dependency berubah
- Method: Dihitung ulang setiap kali template re-render
const items = ref([1, 2, 3, 4, 5])
// Computed: hanya dihitung ulang jika items berubah
const evenItems = computed(() => {
return items.value.filter(n => n % 2 === 0)
})
---template---
<p>Genap: {{ evenItems }}</p>