Using vm.$watch() multiple times vs one time to handle multiple callbacks?

Viewed 239

In one of the requirements, I need to dynamically add the watch to the same object (in parent component) for different callbacks (belongs to multiple sub components). for example:

addWatch(callback){

    this.$watch(()=>{
    ---
    return **this.a**
    },callback)
}

I have the following queries:

  1. With the number of sub components increase, would it cause a performance issue in VUEJS? (IF yes Is there any threshold)
  2. Would there be any performance improvement if I rather keep an array of callbacks and create watch once to loop through this array and execute each of the methods if watch triggers? Or Does VUEJS manage it internally?

Thanks in advance!

1 Answers

It is best to call watch for each thing you want to watch for. That way, vue can optimize and only call your watcher when the acutal variables used in that watcher get changed.

If you watch for the same value, vue is pretty good at optimizing but in that case, it is best to only add one listener because there is still a performance overhead (but this is really micro-optimization, it is normally not worth the effort)

Example:

// Will only get called when a changes
this.$watch(() => this.a, () => {
  this.aText = this.a + "";
});
// Will only get called when b changes
this.$watch(() => this.b, () => {
  this.bText = this.b + "";
});

Related