How does computed differ from a regular method?
computed and a regular method in Vue look similar - both can "compute" something.
But they work in fundamentally different ways.
Here's the main point:
computed is cached and recalculated only when its dependencies change. method is executed again every time on render.
Let's break this down as clearly as possible.
1. The main difference
computed - a cached value
If the dependent data has not changed → Vue does NOT run the function again.
method - always recalculated
The method is called every time the component renders.
An example showing the difference
<script setup>
import { ref, computed } from 'vue'
const count = ref(1)
const computedDouble = computed(() => {
console.log("computed called")
return count.value * 2
})
function methodDouble() {
console.log("method called")
return count.value * 2
}
</script>
<template>
<p>{{ computedDouble }}</p>
<p>{{ methodDouble() }}</p>
</template>Behavior:
computed:
- Will print
"computed called"once, - until
countchanges - it won't be called again.
method:
- Will print
"method called"every time it renders, - sometimes many times in a row.
2. Behavior on render
| What it does | computed | method |
|---|---|---|
| Caches the result | Yes | No |
| Runs on every render | No | Yes |
| Recalculates only when dependencies change | Yes | No |
| Used as a variable | Yes | No (as a function) |
3. When to use computed?
Use computed when:
the value depends on other reactive data you need derived state performance matters the value is used in the template
Examples:
- filtering an array
- formatting a date
- counting the number of items
- converting a string to UPPERCASE
- complex logic rendered into the template
4. When to use method?
A method is needed when: you need to perform an action the calculation should NOT be cached you need side effects this is not derived state
Examples:
- sending a request
- logging
- changing state
- handling clicks
Summary (briefly)
computed:
- like a variable
- cached
- recalculated only when dependencies change
- optimized for performance
method:
- like a function
- called on every render
- not cached
- suited for actions, not computations
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.