Summary of the use of vue Watch and Computed

Summary of the use of vue Watch and Computed

01. Listener watch

(1) Function

  • watch: used to monitor data changes in data, and only executed when the monitored attribute value changes
export default {
    data() {
        return {
            number: 1
        }
    },
    watch:{
        // Ordinary monitoring method, here it means monitoring the number attribute in data // The first parameter indicates the new value after the change, and the second parameter indicates the old value before the change number(newVal,oldVal){
            console.log(newVal);
            console.log(oldVal);
        }
    }
}

(2) Properties and methods

  • immediate: Indicates that after the component is created, the property is monitored immediately. When the value is initially bound, it is set to: immediate: true
  • Handler: Used when monitoring objects. When changes occur, execute the method in the handler.
  • deep: Indicates deep monitoring of changes in properties within objects and arrays. Set to: deep: true
export default {
    data(){
        return {
            number: 1
        }
    },
    watch:
        // Listen for the number attribute number: {
			handler(newVal, oldVal){
                
            },
            immediate: true, // Listen immediately}
    }
}

(3) Monitoring object

  • Can monitor direct assignment operations of objects
    • But you cannot monitor the addition, modification, or deletion of object properties.
export default {
    data() {
        return {
            obj: {
                a: 1
            }
        }
    },
    watch:
        obj: {
            handler(newVal){
                console.log('Listened to', newVal)
            },
            immediate: true
        }
    },
    created(){
        // Cannot be monitored because it is a modification operation on the attribute // Print once, and the print result is the modified value,
        this.obj.a = 2 

        // It can be monitored because it is a direct assignment operation on the object // Print twice (immediate monitoring will print once, and modification will print once)
        this.obj = { a: 2} 
    }
}

Because Vue will perform getter/setter conversion process on the property when initializing the instance

So the property must exist on the data object in order for Vue to transform it, so that it can be responsive

Therefore, Vue cannot detect operations such as adding, deleting, and modifying object properties.

By default, the handler only monitors changes in references to internal properties of the object.

Therefore, it will only listen when we perform assignment operations.

  • You can directly monitor a property value of an object
    • If this property is a basic type value, you can monitor it normally.
export default {
    watch:
        'obj.a': {
            handler(newVal){
                console.log(newVal)
            }
        }
    },
    created(){
        // Both of the following can be monitored and printed twice this.obj.a = 2
        this.obj = { a:2 }
    }
}
  • You can use the deep property for deep monitoring
    • You can only monitor changes to existing properties, but not new properties.
    • Vue cannot monitor this.$set to modify the changes of the original attributes

This is because this.$set() is equivalent to changing the initial value in data

It can trigger monitoring, but the changes are not reflected, that is, newVal === oldVal

export default {
    watch:
        obj: {
            handler(newVal){
            	console.log(newVal)
            },
            deep: true,
            immediate: true
        }
    },
    created(){
        // After deep monitoring, changes in attributes can also be monitored directly // Print twice (because of immediate)
        this.obj.a = 2
        
        // Unable to monitor the addition of object properties // Print once, and the print result is the object with the newly added properties // That is, it will only be executed once due to immediate, and print out {a:1,b:2}
        this.obj.b = 2
        
        // The monitoring can be triggered, but the changes cannot be monitored // Printed twice, both values ​​are {a:2}, which cannot reflect the changes this.$set(this.obj, 'a', 2)
    }
}

(4) Listening array

  • Can monitor
    • Direct assignment of arrays
    • Add, modify, and delete operations through array methods
    • Array operations via the this.$set() method

Array methods such as pop(), push(), etc., and this.$set(arr, index, newVal) method

They can trigger monitoring, but cannot reflect changes, i.e. newVal === oldVal

  • Unable to monitor
    • Unable to monitor the addition, deletion, and modification operations of non-array methods of arrays
    • It is not possible to monitor changes in the array directly through index values
    • Unable to monitor changes in array length
export default {
    data() {
        return {
            arr: [1]
        }
    },
    watch:
        arr: {
            handler(newVal, oldVal) {
                console.log('New:', newVal)
                console.log('old:', oldVal)
            },
            immediate: true
        }
    },
    created() {
        // Can be monitored --- directly assign the entire array this.arr = [2]
        
        // Unable to monitor --- index assignment, length modification this.arr[1] = 2
        this.arr[0] = 2
        this.arr.length = 2
        
        // Can trigger monitoring, but cannot monitor changes => the new and old values ​​are the same this.arr.push(2)
        this.$set(this.arr, 0, 2)
    }
}

02. Computed properties

(1) Set method for computing attributes

  • Computed properties can be written as an Object instead of a Function. However, in the Function form, we use its get method by default. When written as an Object, we can also use its set method.
computed: {
  fullName:
    get () {
      return `${this.firstName} ${this.lastName}`;
    },
    set (val) {
      const names = val.split(' ');
      this.firstName = names[0];
      this.lastName = names[names.length - 1];
    }
  }
}

When executing this.fullName = 'Aresn Liang', the computed set will be called, and firstName and lastName will be assigned to Aresn and Liang.

Computed can depend on other computed or even other components’ data.

(2) Difference

  • Computed properties and listeners
    • Computed properties are: monitoring changes in dependent values
      • As long as the dependency value remains unchanged, the cache will be read directly for reuse
      • Computed properties cannot respond to data changes in asynchronous operations
      • Need to call manually
    • The listener watch is: monitor the changes of attribute values
      • Whenever the property value changes, a callback function can be triggered
      • Listeners can respond to changes in data during asynchronous operations
      • Automatic trigger
  • Computed properties and methods
    • methods is a method, it can accept parameters, but computed cannot
    • Computed is cacheable, methods are not

(3) Usage scenarios

  • When a property is affected by multiple properties, computed is needed.
  • When one piece of data affects multiple pieces of data, you need to use watch, such as searching for data

The above is a detailed summary of the use of vue Watch and Computed. For more information on the use of vue Watch and Computed, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed examples of the difference between methods watch and computed in Vue.js
  • How to understand the difference between computed and watch in Vue
  • What are the differences between computed and watch in Vue
  • Detailed explanation of watch and computed in Vue
  • The difference and usage of watch and computed in Vue
  • Difference between computed and watch in Vue
  • The difference and usage of watch, computed and updated in Vue
  • A brief understanding of the difference between Vue computed properties and watch
  • The difference between computed properties, methods and watched in Vue
  • Detailed explanation of the similarities and differences between computed and watch in Vue
  • Analyze the difference between computed and watch in Vue

<<:  MySQL 5.7.18 Installer installation download graphic tutorial

>>:  How to deploy nginx with Docker and modify the configuration file

Recommend

Detailed explanation of Vue routing router

Table of contents Using routing plugins in a modu...

Videojs+swiper realizes Taobao product details carousel

This article shares the specific code of videojs+...

Detailed explanation of the wonderful uses of SUID, SGID and SBIT in Linux

Preface Linux's file permission management is...

Use standard dl, dt, dd tags to discard table lists

Now, more and more front-end developers are starti...

The solution record of Vue failing to obtain the element for the first time

Preface The solution to the problem of not being ...

HTML+CSS+jQuery imitates the search hot list tab effect with screenshots

Copy code The code is as follows: <!DOCTYPE ht...

Introduction to Vue life cycle and detailed explanation of hook functions

Table of contents Vue life cycle introduction and...

How to insert weather forecast into your website

We hope to insert the weather forecast into the w...

Detailed explanation of identifying files with the same content on Linux

Preface Sometimes file copies amount to a huge wa...

Mini Program to Implement the Complete Shopping Cart

The mini program implements a complete shopping c...

How to run top command in batch mode

top command is the best command that everyone is ...

Summary and examples of vue3 component communication methods

The communication modes of vue3 components are as...

Navicat for MySQL scheduled database backup and data recovery details

Database modification or deletion operations may ...

JavaScript to implement simple carousel chart most complete code analysis (ES5)

This article shares the specific code for JavaScr...

Docker uses a single image to map to multiple ports

need: The official website's resource server ...