gogoWebsite

【vue】vue2 and vue3 watch monitoring (listen to multiple data; listen to object properties change, new and old values ​​are the same; etc.)

Updated to 21 days ago
Detailed explanation of the usage of watch listening in vue2 and vue3 (full)

First write a vue page

<template>
	 <div>
		 <h1> Listen to an attribute</h1>
		 <p>Sum: {{ sum }}</p>
		 <button @click="sum++">Click me to add 1</button><br />

		 <h2>Supervising multiple attributes</h2>
  		 <p>{{ tipsmessage }}</p>
  		 <button @click="tipsmessage += 1">Click me to splice 1</button><br />

		 <h1>Supervisor object</h1>
 		 <p>Name: {{ }}</p>
  		 <p>Age: {{ }}</p>
  		 <button @click="++">Click me to add age</button><br />

		 <h1>A certain attribute change of listener object</h1>
  		 <p>Salary: {{ }}</p>
  		 <p>Working years: {{ }}</p>
  		 <button @click=" += 1000">Click me to increase my salary</button>
  		 <button @click="++">Click me to add work years</button>
	 </div>

 </template>

Usage of watch in Vue2

<script>
	 data () {
    	 return {
      		 sum: 12,
      		 tipsmessage: 'hell0',
      		 obj: {
        		 name: 'Old Wang next door',
        		 age: '30',
       		 test: {
          		 Salary: 3000,
          		 year: 1
        	 }
      	 }
     }
   },
   // Method 1: Listen to the changes of a certain attribute value in data. If you want to listen to the changes of multiple attribute values, you can continue to write it in it.
   watch: {
     sum(newVal, oldVal){
    	 ('New value:', newVal)
         ('Old Value:', oldVal)
   	    },
     tipsmessage (newVal, oldVal) {
         ('New value:', newVal)
         ('Old Value:', oldVal)
        }
    }

 // Method 2: Listen to the changes of obj objects in data
 // This kind of monitoring changes in the entire object requires deep, otherwise it cannot be monitored; it cannot monitor changes in a certain attribute value under the object, and the specific value cannot be monitored, the new value and the old value are the same.
	 watch: {
             obj: {
                 handler(newVal, oldVal) {
                     ('New value:', newVal)
                     ('Old Value:', oldVal)
                 },
                 deep: true
             }
         }
 // If you want to listen for specific attribute changes, such as name or age, then you will only execute the handler function. There are two methods: you need to use computed attributes to be used as intermediate layers or wrap the attributes in quotes

 // Method 3: Listen to the changes of a specific attribute under the obj object in data ---- The first method is to use computed as the intermediate layer
		 computed: {
             getValue() {
                 Return
             }
         },
         watch: {
             getValule(newVal, oldVal) {
                 ('New value:', newVal)
                 ('Old Value:', oldVal)
             }
             // Another way to write
             getValue: {
                 handler(newVal, oldVal) {
                     ('New value:', newVal)
                     ('Old Value
                     :', oldVal)
                 }
             }
         }

 // Method 4: Listen to the changes of a specific attribute under the obj object in data --- The second method is wrapped in quotes
		 watch: {
             ''(newVal, oldVal) {
                 ('New value:', newVal)
                 ('Old Value:', oldVal)
             }
             // There is another way to write it
             '': {
                 handler(newVal, oldVal) {
                     ('New value:', newVal)
                     ('Old Value:', oldVal)
                 }
             }
         }
 // Method 5: Listen to the test object in the obj object in data --- There is no good idea for the time being

 // Method 6: Listen to the specific attribute values ​​in the test object in the obj object in data ---- or two methods
 // Method 1: Use computed to make the intermediate layer
		 computed: {
             getValue() {
                 Return
             }
         }
         watch: {
             getValue(newValue, oldValue) {
                 ('New value:', newVal)
                 ('Old Value:', oldVal)
             }
            
             // Another way to write
             getValue: {
                 handler (newVal, oldVal){
                     ('New value:', newVal)
                     ('Old Value:', oldVal)
                 }
             }
         }
        
         // Method 2: Use watch to listen directly, enclose it in brackets
         watch: {
             ''(newVal, oldVal) {
                 ('New value:', newVal)
                 ('Old Value:', oldVal)
             }
            
             // Another way to write
             '': {
                 handler(newVal, oldVal) {
                     ('New value:', newVal)
                     ('Old Value:', oldVal)
                 }
             }
         }
 </script>

Summarize:
1. Listen to the field properties in data in vue2, and directly use watch: { field name (newVal, oldVal) { statement}} to listen to the changes in the field
2. For the changes in objects and their properties in listening to data:
(1) Listen to the entire object: Use the watch: {obj: {handler(newVal,oldVal){ statement}, deep: true}} method. Note that this method can only listen to changes in the entire object, and cannot listen to the specific changes in a certain attribute value under the object. That is, when a certain attribute value under the object changes, using this method to monitor, the handler function will be executed, but the data obtained is the same as the old value (both new values) and the changes cannot be monitored.
(2) There are two ways to listen for a certain attribute under the object:
                   1、Use Computing PropertiescomputedMaking the middle layer,In usewatchmonitor
                   2、The specific properties of an object can be enclosed directly in quotes.,Then use watch
3. Listen to objects in data and some attributes under objects in objects
(1) For the object in the object, I have no good solution at present - but using $set should solve it
(2) There are two ways to listen for a certain property under an object in the object.
1. Use the computed attribute computed as the intermediate layer, and then use watch to listen eg: computed: { getValue() { return }} watch: {getValue(newVal, oldVal) { statement}}
                   2、A specific property value of an object in an object is directly enclosed in quotes.,Then usewatch eg: watch: {‘’(newVal,oldVal){Statement}}

Usage of watch in Vue3

<script>
	 setup() {
		 let sum = ref(122)
         let tipsmessage = ref('hello')
         const obj = reactive({
             name: 'Old Wang next door',
             age: '30',
             test: {
                 Salary: 3000,
                 year: 1
             }
         })

 // Method 1: Listen to a single basic data type (ref)
         watch( sum, ( newVal, oldVal ) => {
             (newVal, oldVal)
         })

 // Method 2: Listen to multiple basic data types (ref)
         watch( [ sum, tipsmessage ], ( newVal, oldVal ) => {
             // [122, 'hello1'] After listening, I found that the new value and the old value are both arrays
             ( newVal, oldVal )
         })

 // Method 3: Listen to the object (reactive)
         /*
        	 The current problems with vue3:
        		  Responsive use of proxy proxy cannot correctly listen and get the old value of the object
     			 2. Forced to enable deep monitoring, and the shutdown is invalid (the deep configuration is invalid)
         */
         watch(obj, (newVal, oldVal) => {
             ('New value:', newVal)
             ('Old Value:', oldVal)
         })
         // This method cannot monitor changes in specific attribute values, it can only monitor changes in overall obj, and the deep configuration is invalid


 // Method 4: Listen to a certain attribute value under the object --- This can monitor changes in specific attribute values
         watch(()=>, ( newVal, oldVal) => {
             ('New value:', newVal)
             ('Old Value:', oldVal)
         })

 // Method 5: Listen to the changes in multiple attribute values ​​under the object
         watch([() => , () => ], (newVal, oldVal) => {
             ('New value:', newVal)
             ('Old Value:', oldVal)
             // This prints out in an array form
         })
 // Method 6: Listen to the changes of the entire object under the object --- Add deep, this writing method can only listen to the changes of the entire object, and cannot obtain the changes of a specific attribute value under the object in the object, that is, the printed new value and the old value are the same

		 watch(() => , (newVal, oldVal) => {
      		 ('New value 2', newVal)
      		 ('Old Value', oldVal)
    		 }, { deep: true })
		 // Another way to write
		 watch(, (newVal, oldVal) => {
      		 ('New value 1', newVal)
      		 ('Old Value', oldVal)
    		 }, { deep: true })

 // Method 7: Listen to the changes in specific attribute values ​​within the object under the object
         watch(() => , (newVal, oldVal) => {
             ('New value:', newVal)
             ('Old Value:', oldVal)
         })

 // Method 8: Listen to the changes in multiple attribute values ​​under the object under the object
         watch([()=>, ()=> ], (newVal, oldVal) => {
             ('New value:', newVal)
             ('Old Value:', oldVal)
         })

         return {
        	 sum,
        	 tipsmessage,
        	 obj
         }
	 }
 </script>

Summarize:
1. For ref type data, you cannot use the method of ()=> field name, but use direct writing value for monitoring. See the case one and two
2. For reactive type data, do not use the method of directly writing attribute names: watch(property name, (newVal, oldVal)=>{}), because although this method can execute functions, it cannot monitor changes in specific attribute values, and the printed new values ​​are the same as the old values. To use watch(()=> attribute name, (newVal, oldVal)=>{}) method, you can get the value change correctly