Vue 2: when to use computed and when to use methods
A simple Vue 2 question that taught me to think more carefully about derived state, caching and responsibility inside a component.
The question
While building interfaces with Vue 2, I noticed that it was very easy to put any logic inside methods. It worked, but it didn't always express correctly what that logic represented. The question was: if a function only calculates a value from the current state, should it really be a method?
What I understood
A computed property describes a derived value. It tracks its reactive dependencies and reuses the result as long as those dependencies don't change. A method, on the other hand, runs again every time it is called during rendering.
The difference isn't only performance. It's also semantics. If fullName depends on firstName and lastName, computed communicates that fullName is part of the screen's derived state. submitForm, by contrast, is an action and makes more sense as a method.
A simple example
In a form, I can keep firstName and lastName in data and declare fullName as a computed. If either one changes, Vue recalculates the full name. To validate and submit the form, I use methods, because there is an explicit action and possibly a side effect.
Before I understood the difference well, this same form looked like this:
export default {
data() {
return {
firstName: '',
lastName: ''
}
},
methods: {
fullName() {
return `${this.firstName} ${this.lastName}`.trim()
},
submitForm() {
if (!this.fullName()) return
this.$emit('submit', { fullName: this.fullName() })
}
}
}
In the template, that becomes {{ fullName() }} — a function call that re-runs on every render, even when firstName and lastName haven't changed. With computed, the same component looks like this:
export default {
data() {
return {
firstName: '',
lastName: ''
}
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`.trim()
}
},
methods: {
submitForm() {
if (!this.fullName) return
this.$emit('submit', { fullName: this.fullName })
}
}
}
Now fullName is accessed as a property in the template ({{ fullName }}, no parentheses) and only recalculates when firstName or lastName change — the result stays cached between renders. submitForm stays in methods, because it represents an action with a side effect ($emit), not a derived value.
Conclusion for now
This small distinction improved the readability of my components. I started asking whether the code represents a value or an action. When it represents a derived value, computed is usually the first option; when it represents behavior, methods tends to be clearer.