1. Computed introduction

Computed is used to monitor self-defined variables, which are not declared in data but are defined directly in computed and can be used directly on the page.

// Use {{MSG}} <input V-model ="name" /> // calculate attributes computed:{MSG :function(){return this.name}}Copy the code

In the input box, when changing the value of the name, MSG will also change. This is because computed listens to its attribute MSG and finds that if name changes, the MSG updates immediately.

Note: MSG cannot be defined in data, otherwise an error will be reported.

1.1. Usage of GET and set

<input V-model ="full" ><br> <input v-model="first" ><br> <input v-model="second" > data(){return{first:' first ', Second :' sister '}}, computed:{full:{get(){// The callback function executes when it needs to read the current attribute value, Return this.first + ' '+ this.second}, set(val){// Monitor the current value of the property. Let names = val.split(") this.first = names[0] this.second = names[1]}}}Copy the code

Get method: When first and second change, the get method is called to update the value of full.

Set method: The set method is called when the value of full is changed. Val is the latest value of full.

1.2. Calculate the attribute cache

We can also achieve this effect through method, splicing data, the code is as follows.

< div > {{full ()}} < / div > data () {return {first: 'beauty', the second: 'sister'}}, methods:{ full(){ return this.first + ' ' + this.second } },Copy the code

Data can be used multiple times on a page, so let’s combine computed and Method and refer to the data multiple times on a page.

<div> computed values: {{full}} {{full}} {{full}} {{full}} </div> <div> methods Computed values: {{fullt}} {{fullt}} {{fullt}} {{fullt}} < / div > data () {return {first: 'beauty', the second: 'sister'}}, computed:{ full:function(){ console.log('computed') return this.first + ' ' + this.second } }, Methods :{fullt(){console.log(' method ') return this.first + '+ this.second}}Copy the code

The running results are as follows:

Based on the results, it is not hard to see that the data obtained by the method needs to be recalculated several times after it is used several times, but the computed properties are not, but are cached based on their reactive dependencies, and then recalculated when the value of the dependent properties changes. Because it has fewer computations, the performance is higher.

Ii. Introduction to Watch

Watch monitors data changes on Vue instances. In plain English, it detects data declared within data. You can monitor not only simple data, but also objects or object properties.

Demo1: Monitors simple data

<input V-model ="first" > <br> data(){return{first:' beautiful ',}}, watch:{first(newVal, Console. log('oldVal',oldVal) {console.log('oldVal',oldVal) // last value of first}}, The latest value will be printed immediatelyCopy the code

Demo2: monitoring object

When listening on objects, you need to use deep listening.

< input v - model = "per. The name" > the data () {return {per: {name: "qian qian", the age: '18'}}}, watch:{ per:{ handler(oldVal,newVal){ console.log('newVal',newVal) console.log('oldVal',oldVal) }, deep:true, } },Copy the code

When per.name is changed, newVal and oldVal are the same, because the pointer they store points to the same place. Therefore, although the depth monitor can monitor the object change, it cannot detect the specific attribute change.

Demo3: Listens to a single property of the object

// Method 1: <input v-model="per.name"> data(){return{per:{name:' qianqian ', age:'18'}}}, watch:{ 'per.name':function(newVal,oldVal){ console.log('newVal->',newVal) console.log('oldVal->',oldVal) } },Copy the code

You can also use computed as an intermediate conversion, as follows:

// Method 2: Computed <input V-model ="per.name"> data(){return{per:{name:' qianqian ', age:'18'}}}, Watch :{perName(){console.log('name changed ')}}, computed:{perName:function(){return this.per.name}},Copy the code

Demo4: Listens for the value passed by the props component

props:{ mm:String }, Log ('oldV',oldV) console.log('oldV',oldV)}} // Use immediate watch:{mm:{  immediate:true, handler(newV,oldV){ console.log('newV',newV) console.log('oldV',oldV) } }Copy the code

If you do not use immediate, the mm on which watch listens does not print when the page is first loaded.

If immediate is used, newV 11 oldV undefined is also displayed during the first loading.

Immediate Triggers the callback function when the component is loaded.

Three, the difference between the two

3.1. For computed

  • Data for computed monitoring is not declared in the data
  • Computed does not support asynchracy, and you cannot listen for changes in data when there are asynchronous operations in computed
  • Computed with caching, pages are re-rendered, and if the value does not change, the computed results are returned without recalculation
  • If an attribute is computed by other attributes, the attribute depends on other attributes, usually computed
  • When computed to compute property values is a function, the default is to use the GET method. If the property value is the property value, the property has a get and set method that is called when the data changes.
Computed :{// Attribute values are function perName:function(){return this.per.name}, // Attribute values are attribute values full:{get(){}, set(val){}},Copy the code

3.2 for Watch

  • The monitored data must be declared in data or props data
  • Support asynchronous operation
  • Without caching, the page is re-rendered without changing its value
  • When the value of an attribute changes, an action needs to be performed
  • Other operations are triggered when the listening data changes. The function takes two arguments:
Immediate: Indicates that the callback function is triggered immediately after the component is loaded. Deep: indicates the depth listening function, which is used for complex data, such as listening objects. Note: After the object adds depth listening, the output is the same as the old and new values.Copy the code

Computed pages are not recomputed when they are re-rendered, whereas Watch recalculates, so computed performance is higher.

4. Application scenarios

You should use computed when you need to do numerical calculations and rely on other data, because you can take advantage of the caching nature of computed and avoid recalculation every time you get a value.

You should use Watch when you need to perform asynchronous or expensive operations when data changes. If you need to limit the frequency of operations, you can use computed as an intermediate state.