Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between watch and computed methods in vuejs

Tags:

vue.js

vuejs2

They both seem to do the same thing, and I can't tell when to use which

like image 773
hidar Avatar asked Aug 29 '17 09:08

hidar


1 Answers

Computed properties are just like the data properties. The literal meaning of computed is 'calculated using given values'.

Just as the meaning suggests computed properties are a calculated result of its dependent values(in vuejs data properties, props)

for example:

data:{
    lowerCase: 'abcd'
},
computed:{
    uppercase(){
        return this.lowerCase.toUpperCase();
    }
}

in the above example the computed property uppercase is dependent on data property lowerCase. It converts(computes) the letters into uppercase. whenever lowercase changes , so any template bindings using this computed property automatically update.

Watch properties are more general and in one way more powerful(bit expensive) to watch for changes in data properties. You can perform complex functions, asynchronous tasks in watchers. The example given in the documentation is a good example of using a watcher.

Summarizing the differences:

  1. Computed properties unlike watched properties should return a value.

  2. computed properties are just like data properties and can be used in template using {{ }} but watchers cannot be used. Watchers should perform logic to update the data properties which are used in the template.

like image 99
Vamsi Krishna Avatar answered Oct 08 '22 02:10

Vamsi Krishna