💚 Vue.js Beginner

What are computed properties in Vue?

Answer

Computed properties are derived values that automatically update when their dependencies change. They are cached based on their reactive dependencies — only recomputed when dependencies change, unlike methods which re-execute every render. Composition API: import { ref, computed } from "vue"; const firstName = ref("Alice"); const lastName = ref("Johnson"); const fullName = computed(() => `${firstName.value} ${lastName.value}`);. Options API: computed: { fullName() { return this.firstName + " " + this.lastName; } }. vs Methods: methods re-execute every time the template renders (no caching). {{ expensiveCalc() }} recalculates on every render; {{ expensiveComputed }} only recalculates when its dependencies change. Use computed for derived state that's used multiple times. Use methods for operations with side effects or when you don't want caching. Writable computed: const fullName = computed({ get: () => firstName.value + " " + lastName.value, set: (val) => { const parts = val.split(" "); firstName.value = parts[0]; lastName.value = parts[1]; } });. Setting fullName splits it into first and last. Best practices: keep computed getters free of side effects (no mutations, no async operations). Use watchers for side effects triggered by data changes.