This is the 13th day of my participation in the August More Text Challenge.More challenges in August
In vUE’s project, we often need to deal with changes in data, and then we need to use watch and computed. Since both are attributes that trigger changes, what are the similarities and differences between them?
1. Compute attributes computed
Features:
- Support caching, only dependent data changes, will recalculate;
- Asynchronous operations are not supported. In computed asynchronous operations, data changes cannot be monitored.
- Computed attribute values are cached by default, and computed attributes are cached based on their responsive dependencies. That is, a value computed from the data in props declared in data or passed by the parent component;
- If a property is computed by some other property, and that property depends on the other property is a many-to-one or one-to-one, generally computed;
- If computed property values are functions, then by default the get method is used, and the return value of the function is the property value of the property. In computed, attributes have a GET and a set method, which are called when data changes.
<template>
<div>
<el-input v-model="firstText"></el-input>
<el-input v-model="lastText"></el-input>
<el-input v-model="mergeText1"></el-input>
<el-input v-model="mergeText2"></el-input>
</div>
</template>
<script>
export default {
data() {
return {
firstText:'hello'.lastText:'world'}; },computed: {mergeText1(){
return this.firstText + ' ' + this.lastText;
},
mergeText2: {/* Reverse assignment to firstText and lastText */ via mergeText2
// getter
get() { // The callback function executes when it needs to read the current value of the property, calculating and returning the current value of the property based on the relevant data
return `The ${this.firstText} The ${this.lastText}`;
},
// setter
set(val) { Val is the latest value of the fullName attribute
const names = val.split(' ');
console.log(names);
this.firstText = names[0];
this.lastText = names[names.length - 1]; }}}};</script>
Copy the code
Advantages:
- When the value of the data variable is changed, the entire application is re-rendered and the VUE is re-rendered into the DOM by the data. At this point, if we use names, the method is called along with rendering, and computed does not recalculate, resulting in less performance overhead. Caching makes a lot of sense when new values require a lot of computation;
- Computed attributes are recalculated and cached only if the data on which computed depends changes. When other data is changed, computed properties do not recalculate, thus improving performance;
- You can use computed when you get a value that needs some processing;
Application Scenarios:
2. Listen property Watch
Features:
- Does not support cache, data changes, will directly trigger the corresponding operation;
- Watch supports asynchronous operations;
- The listening function takes two arguments, the first of which is the latest value; The second argument is the value before input;
- When an attribute changes, you need to perform the corresponding operation, one-to-many.
- The listening data must be the data declared in data or passed in props by the parent component. When other operations are triggered when data changes, the function takes two parameters: immediate: The callback function is triggered immediately after the component is loaded. Deep: deep monitoring; To detect changes in an object’s internal value, for example, changes in the contents of an object in an array, note that you do not need to do this to listen for changes in an array. Note: Deep cannot listen for array changes or object additions, as in vUE array mutations, only when triggered in a responsive manner.
Note: This approach is most useful when you need to perform asynchronous or expensive operations when data changes, which is the biggest difference between computed and computed.
2.1 General usage: Listen for a single variable or an array
<template>
<div>
<el-input v-model="firstText"></el-input>
<el-input v-model="lastText"></el-input>
<el-input v-model="mergeText"></el-input>
</div>
</template>
<script>
export default {
data() {
return {
firstText:'hello'.lastText:'world'.mergeText:' '}; },watch: {This event is triggered when firstText changes, changing the value of mergeText
firstText(newText,oldText){
console.log(newText, oldText);
this.mergeText = newText + ' ' + this.lastText; }}};</script>
Copy the code
2.2 Listening for simple data types
<template>
<div>
<el-input v-model="mergeText"></el-input>
</div>
</template>
<script>
export default {
data() {
return {
mergeText:' '}; },watch: {// mergeText is triggered when the value changes
mergeText(newval,oldVal){
console.log(this.mergeText,newval,oldVal); }}};</script>
Copy the code
2.3 Monitoring Complex Data (Deep Monitoring)
When deep is not used, when we change the value of obj. A, watch cannot listen for changes in data. By default, handler only listens for changes in attribute references, that is, only one layer.
Immerdiate properties: You can execute a handler immediately by declaring the immediate option true.
<template>
<div>
<el-input v-model="obj.text"></el-input>
</div>
</template>
<script>
export default {
data() {
return {
obj: {text:'hello'}}; },watch: {// Listen to object obj change
obj:{
handler (newVal,oldval) {
console.log(newVal,oldval)
},
deep: true.immediate: true}}};</script>
Copy the code
By using deep: true, we can add a listener event to the properties of obj, which will increase the performance overhead. Whenever we change any property value in OBJ, it will trigger handler.
Properties can be obtained directly from the object. Properties method
<template>
<div>
<el-input v-model="obj.text"></el-input>
</div>
</template>
<script>
export default {
data() {
return {
obj: {text:'hello',}}; },watch: {// Listen for the object's single property text
'obj.text':{
handler (newVal,oldval) {
console.log(newVal,oldval)
},
immediate: true.// This property executes a handler first}}};</script>
Copy the code
Matters needing attention:
- The function name in watch must be the attribute name in the dependent data;
- The function in Watch does not need to be called. As long as the attribute on which the function depends is changed, the corresponding function will be executed.
- The function in Watch will take two arguments: the new value and the old value;
- By default, watch cannot monitor object changes. If it needs to be monitored, it needs to be monitored in depth. In depth monitoring, the handler function needs to be configured and deep is set to true. (because it only listens for changes in the address of the object, not the value);
- By default, watch does not listen on the first load. If you want to listen on the first load, you need to set immediate:true.
- In special cases, watch cannot listen for changes in the array: it changes the data in the array by subscript; Change the length of the array by length;
Solution:
$set(target, propertyName/index, value); Parameter: target {Object | Array}, propertyName/index {string | number}, value {any}this.$set(this.arr,0.100);
Copy the code
$delete(target, propertyName/index) : target {Object | Array}, propertyName/index {string | number}this.$delete(this.arr,0)
Copy the code
- The watche function name must be handler, otherwise it will have no effect, because watche r corresponds to a call to handler
Application Scenarios:
Methods the methods
Methods are different from the previous ones. We usually write methods here and execute them again as soon as we call them. There are trigger conditions.
Note: Computed is cached, which means that computed attributes get values directly from the cache, and multiple visits return the computed results, as long as there is no corresponding data update for their dependencies.
4. To summarize
In terms of computed and watch, there is a semantic difference between computing and observation. Calculation is to obtain data through variable calculation, while observation is to observe a specific value and make corresponding changes according to the changes of the observed. It cannot be mixed with each other in a specific scene, so we still need to pay attention to the rationality and semantics of API application.