SoFunction
Updated on 2025-04-04

Several methods of using Vue watch monitoring

1. Several ways to use watch

1. Listen to the changes in msg data through watch.

watch: {
    msg(oldValue, newValue) {
        (oldValue)
        (newValue)
    }
}

2. Listen to the changes in obj data through watch. (Deep monitoring deep)

data() {
    return {
        obj: {
            'name': "Zhao",
            'age': 18
        },
    }
},
watch: {
    obj: {
        handler(oldValue,newVal) {
             (oldValue)
             (newValue)
        },
        deep: true  // In-depth monitoring    }
}

3. Monitor the changes in data data through watch. When the data changes, execute the change method.

watch: {
    data: 'change' // The value can be the method name of the method},
methods: {
    change(oldVal,newVal){
 (oldVal,newVal)
  }
}

2. The immediate, handler and deep attributes in watch

1. immediate attribute

There is a feature when using watch, that is, when the value is bound for the first time, the listening function will not be executed, and it will only be executed when the value changes. If we need to execute the function when the value is initially bound, we need to use the immediate attribute.

2. Handler attribute

How to execute specific methods in watch

3. deep attribute

When it is necessary to listen for changes to an object, ordinary watch methods cannot listen for changes to the internal properties of the object. At this time, deep attributes are required to deeply monitor the object. Array strings generally do not need to

data() {
    return {
        obj: {
            'name': "king",
            'age': 18
        },
    }
},
watch: {
    obj: {
        // Execution method        handler(oldValue,newVal) {
             (oldValue)
             (newValue)
        },
        deep: true, // In-depth monitoring        immediate: true  // Execute the first change    }
   // If you only need to listen for one property value in the object, you can do the following optimization: Use strings to listen for object properties:    '': {
        // Execution method        handler(oldValue,newVal) {
             (oldValue)
             (newValue)
        },
        deep: true, // In-depth monitoring        immediate: true  // Execute the first change    }
}

This is the end of this article about several methods of using Vue watch monitoring. For more related Vue watch monitoring content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!