Vue 3 Basic
What is the difference between computed and methods in Vue?
Core Difference: Caching
computed is cached — it only re-evaluates when its reactive dependencies change.methods re-execute every time they are called — no caching.
Example
import { ref, computed } from 'vue'
const count = ref(0)
// computed: cached — only re-runs when count changes
const doubled = computed(() => {
console.log('computed ran')
return count.value * 2
})
// methods: runs every time it's called
function getDoubled() {
console.log('method ran')
return count.value * 2
}
<template>
<!-- Rendered 3 times, but computed only runs ONCE -->
<p>{{ doubled }}</p>
<p>{{ doubled }}</p>
<p>{{ doubled }}</p>
<!-- Called 3 times, runs 3 times -->
<p>{{ getDoubled() }}</p>
<p>{{ getDoubled() }}</p>
<p>{{ getDoubled() }}</p>
</template>
Comparison
| Feature | computed |
methods |
|---|---|---|
| Caching | ✅ Yes (skips if deps unchanged) | ❌ No |
| Usage | Access like a property (no ()) |
Call with () |
| Accepts arguments | ❌ No | ✅ Yes |
| Best for | Deriving new data from existing data | Events, side effects |
| Return value | Required | Optional |
When to Use computed?
// ✅ Deriving a new value from existing data
const fullName = computed(() => firstName.value + ' ' + lastName.value)
// ✅ Filtering a list
const activeUsers = computed(() => users.value.filter(u => u.active))
// ✅ Formatting data
const formattedPrice = computed(() => '$' + price.value.toFixed(2))
When to Use methods?
// ✅ Event handlers
function handleClick() { /* ... */ }
// ✅ Side effects (API calls, data mutations)
async function fetchData() { /* ... */ }
// ✅ Needs parameters
function formatDate(date) { /* ... */ }
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
