As the title says, see an example of computed and watch getting the full name in the vue.js official document:
var 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
}
}
})
var var vm = new Vue({
el: '#demo',
data: {
firstName: 'Foo',
lastName: 'Bar'
},
computed: {
fullName: function () {
return this.firstName + ' ' + this.lastName
}
}
})
The rookie said that he doesn’t understand the difference between them. Can’t watch be obtained like computed?
You write less code using computed, there is no major difference
I think there is still a difference, and the two application situations should be distinguished.
Computed properties are computed properties and observations are observations.
As the name suggests, a calculated attribute is another attribute calculated through other variables. fullName recalculates its own value when the two variables it depends on, firstName and lastName, change.
Also, Computed properties have caching. Computed properties are cached based on their dependencies. A computed property is only re-evaluated when its associated dependencies change. This means that as long as neither lastName nor firstName has changed, multiple accesses to the fullName calculated property will immediately return the previous calculated result without having to execute the function again.
Observing watch is to observe a specific value and execute a specific function when the value changes. For example, in the paging component, we can detect the page number and execute the function to obtain data.
You can check the document in more detail: https://cn.vuejs.org/v2/guide...
More readable and generally less code.
Simply speaking, computed is based on cache, and watch is equal to a function. Personally, I think it’s enough as long as you know how to use it. I’ll tell you the specific differences
I think computed attributes should be used more widely