Using watchEffect in Vue.js

What is watchEffect?

  • watchEffect is a function in Vue 3 that allows you to automatically track and react to reactive dependencies.
  • It runs a given function immediately and re-runs it whenever any reactive dependencies change.

Usage of watchEffect :

To use watchEffect , you have to import it from Vue and pass it a function that contains the code you want to run reactively.

import { ref, watchEffect } from 'vue';

export default {
  setup() {
    const count = ref(0);

    watchEffect(() => {
      console.log(`Count is: ${count.value}`);
    });

    function increment() {
      count.value++;
    }

    return {
      count,
      increment
    };
  }
}

In this example, watchEffect logs the value of count every time it changes. The reactive dependency, count, is automatically tracked by watchEffect .

Thank You.

Leave a comment

Your email address will not be published. Required fields are marked *