Vue.js Computed Properties
Computed properties keyword: computed
.
Computed properties are very useful when dealing with complex logic.
Consider the following example of reversing a string:
Example 1
<div id="app">
{{ message.split('').reverse().join('') }}
</div>
In Example 1, the template becomes quite complex and hard to understand.
Next, let's look at an example using computed properties:
Example 2
<div id="app">
<p>Original string: {{ message }}</p>
<p>Reversed string: {{ reversedMessage }}</p>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
message: 'tutorialpro!'
},
computed: {
// Computed property getter
reversedMessage: function () {
// `this` points to the vm instance
return this.message.split('').reverse().join('')
}
}
})
</script>
In Example 2, a computed property reversedMessage
is declared.
The provided function will serve as the getter for the property vm.reversedMessage
.
vm.reversedMessage
depends on vm.message
, and it will update whenever vm.message
changes.
Computed vs Methods
We can use methods instead of computed properties, and both achieve the same effect. However, computed properties are cached based on their dependencies, and they only re-evaluate when the related dependencies change. In contrast, methods are always called again during re-rendering.
Example 3
methods: {
reversedMessage2: function () {
return this.message.split('').reverse().join('')
}
}
Using computed properties can be more performant, but if you do not want caching, you can use methods.
Computed Setter
Computed properties default to only having a getter, but you can also provide a setter when needed:
Example 4
var vm = new Vue({
el: '#app',
data: {
name: 'Google',
url: 'http://www.google.com'
},
computed: {
site: {
// getter
get: function () {
return this.name + ' ' + this.url
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.name = names[0]
this.url = names[names.length - 1]
}
}
}
})
// Calling the setter, vm.name and vm.url will be updated accordingly
vm.site = 'tutorialpro.org http://www.tutorialpro.org';
document.write('name: ' + vm.name);
document.write('<br>');
document.write('url: ' + vm.url);
From the example, when running vm.site = 'tutorialpro.org http://www.tutorialpro.org';
, the setter is called, and vm.name
and vm.url
are updated accordingly.