What is the difference between this.$watch and watch?

Asked 1 years ago, Updated 1 years ago, 72 views

I am a beginner programmer studying Vue.js.

I didn't understand the difference between watch and this.$watch, but
Am I correct in understanding that the two sources I mentioned below move the same way?

I was looking into the text, but I couldn't find a place where my interpretation of whether it was like this or not was pinpointed.

The fuga below is only installed to make it easier to see, but it doesn't make any sense.

data:{
    list: "hoge",
},
methods: {
    fuga: function() {
        // Processing 1
    }
},
watch: {
    list: {
        handler:function(newVal,oldVal){
            // Processing 2
        }
    }
}
data:{
    list: "hoge",
},
methods: {
    fuga: function() {
        // Processing 1
    },
    handler:function(){
        This.$watch('list', function(newVal, oldVal){
            // Processing 2
        }
    }
}

I look forward to your kind cooperation.

javascript vue.js

2022-09-30 11:09

1 Answers

The same movement may be a little different.From the API document (API—Vue.js),

An evaluation expression that the key monitors, and the value is an object with the corresponding callback.The value can be a method name string or an object that contains additional options.A Vue instance calls $watch() for each entry in the object during instantiation.

As you can see, the former code calls $watch upon initialization of that Vue instance.Therefore, the watcher is already running when the instance is ready without further awareness.

However, the latter code means that the watcher is not registered unless this.handler is called even when the instance is initialized.
In addition, you may use it incorrectly as shown in the following example:

<button@click="handler">Register watch handler</button>

Isn't it easy to imagine a duplicate watch handler registered when you use this with the latter code in question?(Furthermore, when combined with the vue-router, the same problem occurs when called during initialization)


2022-09-30 11:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.