computed

  1. Computed is used to calculate a value, and a value can be used directly as an attribute without parentheses.
  2. It dynamically computes new values based on dependent properties and automatically caches them, using the ES6 getter method to compute new properties. If the dependency does not change, the value of computed is not recalculated.

Usage scenario: One data is affected by multiple data.

new vue({
    data: {n:1.m:2,},template:'
      
{{q}}
// can be called directly and without parentheses
.computed:{ q(){ return this.m+this.n } } }) Copy the code

watch

  1. Watch is used to listen on data. It has two parameters, value and oldValue. If there is any property change, it will execute a function.
  2. Watch has two options. The first is immediate, which indicates whether this function is executed on the first render. The second is deep, which means that if you want to listen for an object, you need to see if the object has changed inside.

Usage scenario: One data affects multiple data

new vue({
    data: {q: {n:1.m:2,}},template:` 
      
{{q.n}}
`
.watch: {q:{ handler(){ console.log('the data has changed')},immediate:true.deep:true,}}})Copy the code

conclusion

Both computed and Watch perform callbacks after a change in a dependency or monitored value, but computed recaches computed properties after a dependency change, and watch performs another function after a change in the monitored value. Use computed if the data depends on other data, and watch if you want to listen for data changes.