我是vue.js的初学者。使用计算属性而不是方法的原因是什么?为什么问这个问题是因为计算的属性和方法都做同样的事情
答案 0 :(得分:0)
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.