Vue watchers vs computed properties
Deepika Banoth
Posted on April 3, 2020
From the past few days, I have been spending most of my time in learning and understanding how Vue and its reactivity works.
Today I would like to share my learnings on when to use watchers and computed properties.
To be noted, I am still at beginner level :)
When to use Computed properties
-
Computed Properties can react to changes in multiple properties, so you can use it when you have a variable in your template, that's built from one or more data properties. A simple example would be creating
fullName
from the list offirstName
andlastName
:
computed: { fullName() { return `${this.firstName} ${this.lastName}` } }
Computed Properties are very useful for composing new data from existing sources
-
The output of a computed property is cached, this means that if something independent of the computed property changes and the UI is re-rendered, the cached result will be returned and the property will not be re-calculated, sparing us an expensive operation
For example, consider two counters, in whichcomputedCounter
will be updated fromcomputed button
andmethodCounter
will be updated frommethod button
data: function() { return { computedCounter: 0, methodCounter: 0 }; }, computed: { printMsgComputed: function() { console.log(“printed from computed:”, this.computedCounter); } }, methods: { printMsgMethod: function() { console.log(“printed from method:”, this.methodCounter); } },
HTML:
<div> <button @click=”computedCounter++”>computed button</button> <p>{{ computedCounter }}</p> <br/> <button @click=”methodCounter++”>method button</button> <p>{{ methodCounter }}</p> <br/> {{ printMsgMethod() }} {{ printMsgComputed }} </div>
When the above code is executed and when you click on
computed button
bothprintMsgMethod
andprintMsgComputed
will run.
But when you click onmethod button
you can see that onlyprintMsgMethod
running. You Computed properties creates new reactive properties, so you can use it when you want to reduce a nested property name to a more readable and easy to use one, yet update it when the original property changes
You can also use computed properties when you need to listen to changes of more than one data property
When to use Watchers
- Watchers are useful for cases when you want to perform an action in response to a data property change
- Also Watchers are most useful when you want to perform asynchronous or expensive operations in response to changing data
- You can also use watchers when you only need to listen to one specific property
Also Computed properties are only executed when they are needed to be used whereas Watchers are executed whenever a property is changed.
Correct me if I am wrong or missed something.
Posted on April 3, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.