- Learn by example
Make an RPG
Vue Implementations

Example of Computed properties vs watched properties

Both watch and computed let you set an event handler to be called when a variable changes

Let's take a look at an example of how a watched variable works. Notice, whenever count changes the watch handler gets called.

<div id="app"> <input type="button" v-on:click="inc" value="Increment"/> {{ count }} <br> {{ output }} </div>
var app = new Vue({ el: "#app", data: { count: 1, output: "" }, methods: { inc: function() { this.count++; } }, watch: { count: function( newval, oldval ) { this.output += "Count increased. "; } } });
Change this.count++ to this.count = 2; and rerun it. Does the watch handler get called the first time, second time?

Some key differences between watchers and computed:

  • Watchers watch an existing reactive property, unlike computed which creates a new property
  • Watchers watch only one specific property, unlike computed where any dependent property change can cause recalculation.
  • Watchers have arguments of new and old value.

computed caches a computed value and only recalculates it if it's dependencies change

var app = new Vue({ el: "#app", data: { count: 1, countB: 5, output: "" }, methods: { inc: function() { this.count++; }, incB: function() { this.countB++; } }, computed: { count_plus: function() { this.output += "computed "; return this.count + this.countB; } } });
Comment out the line and rerun it. Does the computed handler get called?
Try to add count_plus in the data object. You will get an error.

If you're accessing a value that needs to be cached you should use a computed value, unless you need some custom caching or fetching strategy. For instance, if you need to do an ajax call, then you'll need to impliment a watcher which can then retrieve the value. Then you can cache it yourself.

Watchers are a more generic type of event handler that you can use for a variety of purposes.

In the next lesson, we will learn about Example of How to pass data to parent component

Get the Latest Tutorial Updates
<< >>