DEV Community

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

Posted on • Edited on

6 1 1 1 1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay