If you are a complete beginner to vue, this might sound weird to you. But I promise you that if you read this article in its entirety, you will have completely understood computed properties and watchers.
You already know how we roll, the following is the code that I suggest you replace within one of your components.
Let us see what we have written.
- There is an input element that binds to the data property called length.
- There is mustache tag that outputs the value of a data property called area.
- But there is no data property called area. Are we dealing with black magic here?
- Just kidding, area is a computed property which can be used/accessed just like a regular data property. It has been listed as a function under the computed attribute of the default vue file export. This function operates upon the length and returns a value.
- Every time the value of length changes, the change is reflected in area.
You could add more computed properties simply by adding more functions with return values, I’ve added a property called volume in the image below.
Let us have a look at the things that we have changed here.
- We have initialized another data property called area.
- There is a new property called watch, it contains a function called length.
- The length function inside the watch property fires up every time the value of length changes.
- The length function takes the new value of length as a parameter, though you could also access it by using this keyword.
The output is similar to the earlier one, just the technique is different. Now we have just written code that does the same thing, in 2 different ways. Let us talk about the questions that must be confusing you right now.
Which one to use when?
Sounds like a tough question to answer. Hmm, not so much to be honest. It is very easy.
Computed properties are used to calculate a new value every-time any of its dependent value changes. Watchers on the other hands are used to run a function every-time the value of one particular data element changes. This function is often used to execute things and modify existing elements. Still confused? Look at the table below.
|React to more than 1 elements||Yes||No|
|Used execute other dependent code.||No||Yes|
|Runs first time the app is loaded.||Yes||No|
Once you get familiar with vue you will realize that for most of the times, you will be tempted and might end up using computed properties for things that should be solved with watchers. Try to avoid It, as it is anti-pattern and might end up making the code messy later.
We learned about computed properties and watchers. Watchers react to the change of a data element and computed properties are used to update a value every-time any of its dependent values change. A lot of people often never truly understand watchers and computed properties, They often believe both of them to be the same, which is incorrect. If you have any questions regarding watchers or computed properties, feel free to drop a comment.