What is the main difference between a method and a computed value in Vue.js?
They look the same and interchangeable.
Stumbled upon the same question. To me it's more clear like this:
v-on directive followed by a method, it knows exactly which method to call and when to call it. // @click
// method clearMessage is only called on a click on this button
/* The method clearMessage is only called on pressing the escape key
and the alertMessage method on pressing the enter key */
v-on directive it will be called every time an event is triggered on the page that updates the DOM (or simply needs to re-render a part of the page). Even when that method has nothing to do with the event being triggered.Uppercase message: {{ messageUppercase() }}
methods: {
messageUppercase() {
console.log("messageUpercase");
return this.message.toUpperCase();
}
}
/* The method `messageUppercase()` is called on every button click, mouse hover
or other event that is defined on the page with the `v-on directive`. So every
time the page re-renders.*/
this word in its function definition.Uppercase message: {{ messageUppercase }}
data() {
return {
message: "I love Vue.js"
}
},
computed: {
messageUppercase() {
console.log("messageUpercase");
return this.message.toUpperCase();
}
}
/* The computed property messageUppercase is only called when the propery message is
changed. Not on other events (clicks, mouse hovers,..) unless of course a specific
event changes the value of message. */
The take away here is that it's best practice to use the computed properties in case a method is not being called with the v-on directive.