vue 3 composition api watch

import { ref, watch } from 'vue';

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

    watch(count, (newValue, oldValue) => {
      console.log(`Count changed from ${oldValue} to ${newValue}`);
    });

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

    return {
      count,
      increment,
    };
  },
};

Explanation:

  1. Import Statements: Import the necessary functions (ref and watch) from the Vue library.

  2. Component Setup: Define the component using the Composition API by exporting the setup() function.

  3. Declare Reactive State: Create a reactive variable count using ref() and initialize it with a value of 0.

  4. Watch for Changes: Use the watch() function to monitor changes to the count variable. When count changes, the callback function receives the newValue and oldValue, and logs the change to the console.

  5. Increment Function: Define an increment() function that increases the value of count by one when called.

  6. Return Values: Return the count variable and the increment() function from the setup() function, making them accessible to the component template for rendering and interaction.