Computed attributes (computed)
For example:
<div id='example'>
<p>Original message: "{{message}}"</p>
<p>Computed reversed message: "{{reversedMessage}}"</p>
</div>
Copy the code
let vm = new Vue({
el: '#example'.data: {
message: 'Hello'
},
computed: {
reversedMessage: function () {
return this.message.split(' ').reverse().join(' ')}}})Copy the code
Computed attribute caching (computed) vs methods (methods)
Use the method to achieve the same effect:
<p>Reversed message: "{{reversedMessage()}}"</p>
Copy the code
methods: {
reversedMessage: function () {
return this.message.split(' ').reverse().join(' '); }}Copy the code
We can define the same function as a method rather than a calculated property. The end result is exactly the same. The difference is that computed attributes are cached based on their dependencies. A calculated property is reevaluated only if its associated dependencies change.
Why cache? Suppose we have A computationally expensive property, A, that iterates through A large array and does A lot of computations. And then we might have other computational properties that depend on A. Without caching, we would inevitably execute A’s getter multiple times! If you don’t want caching, use methods instead.
Computed attributes (computed) vs. listening attributes (Watch)
Listen to attribute
<div id="demo">{{ fullName }}</div>
Copy the code
var vm = new Vue({
el: '#demo'.data: {
firstName: 'Foo'.lastName: 'Bar'.fullName: 'Foo Bar'
},
watch: {
firstName: function (val) {
this.fullName = val + ' ' + this.lastName
},
lastName: function (val) {
this.fullName = this.firstName + ' ' + val
}
}
})
Copy the code
The code above is imperative. If you use computed transformation:
var vm = new Vue({
el:'#demo'.data: {
firstName: 'Foo'.lastName: 'Bar'
},
computed: {
fullName: function () {
return this.firstName + this.lastName; }}})Copy the code
Evaluate the setter for the property
Calculate properties by default only have getters, but you can provide a setter if you want:
computed: {
fullName: {
get: function () {
return this.firstName + this.lastName;
},
set: function (newValue) {
var names = newValue.split(' ');
this.firstName = names[0];
this.lastName = names[names.length - 1]; }}}Copy the code
When vm.fullName = ‘John Doe’ is run, the setter is called and vm.firstName and vm.lastName are updated accordingly.
Listener (watch) is used
While computing properties is more appropriate in most cases, sometimes a custom listener is required. The Watch option provides a more generic way to respond to changes in data. This approach is most useful when asynchronous or expensive operations need to be performed when data changes.