Understanding Computed Properties and Watchers in Vue.js: Usage, Differences, and Examples
This article explains Vue.js computed properties and watchers, detailing their definitions, usage scenarios, code examples, differences, deep and immediate options, and when to prefer one over the other for reactive front‑end development.
In this article, the author introduces the concepts of computed properties and watchers in Vue.js, explaining their purpose, usage scenarios, and differences.
Computed properties automatically track dependencies and cache results; they consist of get and optional set functions. Example code shows a computed fullName with getter and setter.
computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}The article compares computed properties with ordinary data properties and with methods, highlighting that computed values are cached while methods are not, and that computed can accept parameters via closures.
data:{
msg:'浪里行舟',
},
computed:{
msg2:function(){ return '浪里行舟'; },
reverseMsg:function(){
return this.msg.split(' ').reverse().join(' ');
}
}Watchers provide a generic way to observe data changes. The basic syntax and a deep‑watch example are presented.
watch: {
a: function(val, oldVal) {
this.b.c += 1;
},
"b.c": function(val, oldVal) {
this.b.d += 1;
},
e: {
handler: function(val, oldVal) {
this.h.push("浪里行舟");
},
deep: true
}
}Deep and immediate options are explained, with code showing how to watch a nested object and trigger callbacks immediately.
watch: {
obj: {
handler: function(newVal, oldVal) {
console.log(newVal);
},
deep: true,
immediate: true
}
}A debounce example demonstrates using a watcher to delay updates until the user stops typing for one second.
watch: {
firstName: function(val) {
clearTimeout(this.firstTimeout);
this.firstTimeout = setTimeout(() => {
this.fullName = val + ' ' + this.lastName;
}, 1000);
},
lastName: function(val) {
clearTimeout(this.lastTimeout);
this.lastTimeout = setTimeout(() => {
this.fullName = this.firstName + ' ' + val;
}, 1000);
}
}Finally, the article concludes that computed properties are best for template rendering of derived values, while watchers are suited for executing complex logic in response to data changes.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.