DEV Community

Cover image for Multiple watchers in Vue 3
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on • Updated on

Multiple watchers in Vue 3

In Vue 3, you can use the watchEffect function to create a watcher that automatically tracks the reactive dependencies of a component. To create multiple watchers, you can use watchEffect in combination with the watch function. Here's an example of how to use multiple watchers in Vue 3:

<template>
  <div>
    <input v-model="name" />
    <input v-model="email" />
  </div>
</template>

<script>
import { ref, watchEffect, watch } from 'vue';

export default {
  setup() {
    const name = ref('');
    const email = ref('');

    // First watcher using watchEffect
    watchEffect(() => {
      console.log('Name changed: ', name.value);
    });

    // Second watcher using watch
    watch(email, (newValue, oldValue) => {
      console.log('Email changed: ', newValue, oldValue);
    });

    return {
      name,
      email,
    };
  },
};
</script>

Enter fullscreen mode Exit fullscreen mode

In this example, the watchEffect function is used to create a watcher that logs to the console whenever the name property changes. The watch function is used to create a second watcher that logs to the console whenever the email property changes.

By using watchEffect and watch together, you can create multiple watchers that track different reactive dependencies in your component. Note that the watch function is useful when you want to watch a specific property or set of properties, whereas watchEffect will watch all reactive dependencies.

Happy Reading...... ❤️ 🦄

Follow me, for more updates

Top comments (0)