I am a beginner to vue.js. What is the reason to use computed property instead of methods. Why am asking this question is, because the both computed property and methods do the same thing
1 Answer
Methods can get attributes and need to be called manually, computed is not. Also you no need to clone code while multiple using. Think about computed properties like a shortcut to you additional logic.
Putting too much logic in your templates can make them bloated and hard to maintain. For example:
<div id="example">
{{ message.split('').reverse().join('') }}
</div>
The same, using computed property:
<div id="example">
{{ reversedMessage }}
</div>
Vue code:
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
// a computed getter
reversedMessage: function () {
// `this` points to the vm instance
return this.message.split('').reverse().join('')
}
}
})
Difference
But main difference as i think, is caching. When you call method 5 times, you get 5 computings. On the other side a computed property is computing only once (when changing), and then return a cached value.