Difference and usage of watch and computed in vue

  • 2021-08-06 20:59:13
  • OfStack

computed calculation attribute description:

computed is cached based on responsiveness dependencies. Only when the dependency data changes will it be recalculated (when re-rendering is triggered, computed will not recalculate if the dependency data does not change). If it does not change, the calculation property will immediately return the previously cached calculation results.

Asynchrony is not supported. It is invalid when there is asynchronous operation in computed, and it cannot listen for the changing value of data.

Members in computed can define only 1 function as a read-only attribute or get/set as a read-write attribute

If an attribute is computed from another attribute, the attribute depends on the other attribute, either a many-to-1 or a 1-to-1, using computed.

The following computed properties will not be updated because Date. now () is not a responsive dependency:


computed: {
 now: function () {
 return Date.now()
 }
}

In contrast, whenever a re-rendering is triggered, the calling method will always execute the function again.

Why do we need caching? Suppose we have a computational property A with high performance overhead, which needs to traverse a huge array and do a lot of computation. Then we may have other computed attributes that depend on A. Without caching, we will inevitably execute getter of A many times! If you don't want to have cache, please use method instead.

watch Listening Attribute Description:

When caching, data change or re-rendering is not supported, the corresponding operation will be triggered directly.

watch supports asynchronous

When one attribute changes, the corresponding operation needs to be performed; watch is used for 1-to-multitime and 1-to-multitime.

The listening data must be declared in data or passed from the parent component in props, When the data changes, trigger other operations. The function has two parameters. immediate: Component loading immediately triggers callback function execution. deep: Deep monitoring. In order to find changes in internal values of objects, complex types of data are used, such as changes in object contents in arrays. Pay attention to monitoring changes in arrays without doing so. Note: deep can not listen to changes in the array and the addition of objects, reference vue array variation, only in a responsive way to trigger will be monitored.

The difference between watch and computed is:

Similarities:

Both of them observe the changes of page data.

Differences:

computed is calculated only when the dependent data changes, and the data is cached. watch needs to execute the function every time. watch is more suitable for asynchronous operation when data changes.

Use reference official documents

Use of computed

Type: {[key: string]: Function {get: Function, set: Function}}

Details:

The computed attributes will be mixed into the Vue instance. this contexts for all getter and setter are automatically bound to Vue instances.

Note that if you use the arrow function for a computed property, this does not point to the instance of the component, but you can still access its instance as the first argument of the function.


computed: {
 aDouble: vm => vm.a * 2
}

The result of the computed attribute is cached and will not be recalculated unless the dependent responsive property changes. Note that if a dependency (such as non-responsive property) is outside the instance scope, the evaluated property will not be updated.

Example:


var vm = new Vue({
 data: { a: 1 },
 computed: {
  //  Read only 
  aDouble: function () {
   return this.a * 2
  },
  //  Read and set 
  aPlus: {
   get: function () {
    return this.a + 1
   },
   set: function (v) {
    this.a = v - 1
   },
  },
 },
})
vm.aPlus // => 2
vm.aPlus = 3
vm.a // => 2
vm.aDouble // => 4

Use and Interpretation of watch

Type: {[key: string]: string Function Object Array}

Details:

1 object, the key is the expression to be observed, and the value is the corresponding callback function. The value can also be a method name or an object containing options. The Vue instance will call $watch () at instantiation time, traversing every property of the watch object.

Example:


var vm = new Vue({
 data: {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  e: {
   f: {
    g: 5,
   },
  },
 },
 watch: {
  a: function (val, oldVal) {
   console.log('new: %s, old: %s', val, oldVal)
  },
  //  Method name 
  b: 'someMethod',
  //  The callback will be used in the  property  Called when it changes, no matter how deeply it is nested 
  c: {
   handler: function (val, oldVal) {
    ;/_ ... _/
   }, // or handler:' Method name '
   deep: true,
  },
  //  The callback will be called immediately after listening begins 
  d: {
   handler: 'someMethod', // or handler: function(val, oldVal){}
   immediate: true,
  },
  //  You can pass in callback arrays, and they will be expelled by 1 Call 
  e: [
   'handle1',
   function handle2(val, oldVal) {
    /* ... */
   },
   {
    handler: function handle3(val, oldVal) {
     /* ... */
    },
    /* ... */
   },
  ],
  // watch vm.e.f's value: {g: 5}
  'e.f': function (val, oldVal) {
   ;/_ ... _/
  },
 },
})
vm.a = 2 // => new: 2, old: 1

Description: Corresponds to a ~ e above

a: Listening for 1 attribute, which is used when changing values before and after are needed

b: Listening for 1 attribute will not use the value before and after the change, just to execute 1 method, you can use a string instead of a string to represent the method name

c: When listening to an object, watch cannot be triggered when the internal attributes of the object are changed. After setting deep to true, no matter how deep the nesting is, monitoring will be triggered as long as the attribute value is changed. However, this method will be expensive, and the listener will look down layer by layer, adding listeners for each attribute.

If we just listen for a property change of an object, we can do this:


  watch:{
  'user.name':{
   handler: 'method'
  }

 }

d: watch will only be triggered when listening for property changes, and may not be executed when the component is created, so we can set immediate: true, which will enable watch to be executed once immediately after the component is created. You don't have to modify the attributes at create.

handelr: Method for triggering listening execution (if the value before and after the change is needed, it can be replaced by a function)

immediate: Called immediately after listening begins

e: Listening for 1 property, executing multiple functions including callbacks, etc

Note that you should not use arrow functions to define watcher functions (for example, searchQuery: newValue = > this. updateAutocomplete (newValue). The reason is that the arrow function is bound to the context of the parent scope, so this will not point to the Vue instance as expected, and this. updateAutocomplete will be undefined.

Summarize


Related articles: