Home > front end >  Difference between watch and $watch
Difference between watch and $watch

Time:10-21

Just a simple question.

What is the difference between options and instance methods?

Based on watch example, we can implement watcher as an option (https://v3.vuejs.org/api/options-data.html#watch) and a method of an instance (https://v3.vuejs.org/api/instance-methods.html#watch).

From my point of understanding I can implement exactly the same feature with both methods and the only differences would be the syntax and the place of implementation.

If I am mistaken, can somebody explain me based on example the difference between these two?

CodePudding user response:

You are indeed (almost) correct with your assumption.

There is 2 major advantage of this.$watch() though.

  1. You can start watching dynamically
  2. the return-value of this.$watch() is an unwatch function with which you can dynamically stop the watcher during runtime

But that doesn't necessarly mean that you should always use this.$watch() over watch: {}. The opposite. You should always think about what your use case needs

Unwatch-example:

export default {
//..
created(props) {
  const unwatchAge = this.$watch(() => this.user.age, (value, oldValue) => {
    if (value >= 18) {
      alert('You are now allowed to drive a car!');
      unwatchAge(); //we don't need age watching for anything else
    }
  });
}
//...

}

BTW with VUE3 you might wanna look into the watch() / watchEffect() composition API methods.

watch() does the same as watch: {} and this.$watch() and also has an unwatch-method as return-value.

watchEffect() checks any value mentioned inside parameter (function) and puts a watcher on it internally.

watch() Example (composition)

import { toRef, watch} from 'vue';

export default {
//...
setup(props) {
  const age = toRef(props.age);
  const unwatchAge = watch(age, console.log); 
  // no () => age or () => age.value needed as age is a reference by using toRef and references can be handles like this

  setTimeout(() => {
    console.warn('unwatching age!');
    unwatchAge();
  }, 5000);
}
//...

}

watchEffect() Example (composition)

import { toRef, watchEffect} from 'vue';

export default {
//...
setup(props) {
  const age = toRef(props.age);
  
  watchEffect(() => {
    if (age.value >= 18) {
      alert('You are now allowed to drive a car!');
    }
  });
  //vue will internally recognize that age has to be watched here. No telling it manually.
}
//...

}

CodePudding user response:

The main difference from the docs it is that the instance method returns a unwatchable that you can trigger to stop watching a certain property:

const unwatchUsers = this.$watch('users', () => {});

setTimeout(unwatchUsers, 1000);

This is not possible with options API. It is extremely useful to use this unwatch returned by this.$watch when something happens in your app.

Have in mind what is the most appropriate to your use case and use it accordingly

  • Related