0
0
Vueframework~5 mins

Watch and watchEffect in Vue

Choose your learning style9 modes available
Introduction

Watch and watchEffect help you react to changes in data automatically. They run code when something you care about changes.

You want to run code when a specific value changes, like updating a message when a name changes.
You need to perform side effects, like fetching data when a filter changes.
You want to watch multiple values and react when any of them change.
You want to run some code immediately and then again whenever reactive data changes.
Syntax
Vue
import { watch, watchEffect } from 'vue';

// watch syntax
watch(source, callback, options?);

// watchEffect syntax
watchEffect(effectFunction, options?);

watch watches specific reactive sources and runs a callback when they change.

watchEffect runs a function immediately and re-runs it whenever any reactive data inside changes.

Examples
Watch a single reactive value and run code when it changes.
Vue
watch(() => count.value, (newVal, oldVal) => {
  console.log(`Count changed from ${oldVal} to ${newVal}`);
});
Watch multiple reactive values at once.
Vue
watch([() => firstName.value, () => lastName.value], ([newFirst, newLast], [oldFirst, oldLast]) => {
  console.log(`Name changed from ${oldFirst} ${oldLast} to ${newFirst} ${newLast}`);
});
Run code immediately and whenever count changes.
Vue
watchEffect(() => {
  console.log(`Count is now ${count.value}`);
});
Sample Program

This Vue component shows a button and a count. When you click the button, the count increases. The watch function updates the message whenever the count changes.

Vue
<template>
  <div>
    <button @click="count++">Increment</button>
    <p>Count: {{ count }}</p>
    <p>Message: {{ message }}</p>
  </div>
</template>

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

const count = ref(0);
const message = ref('');

watch(count, (newVal, oldVal) => {
  message.value = `Count changed from ${oldVal} to ${newVal}`;
});
</script>
OutputSuccess
Important Notes

Use watch when you want to react to specific data changes with old and new values.

Use watchEffect for simpler cases where you want to run code immediately and track dependencies automatically.

Remember to clean up side effects if needed inside watch or watchEffect to avoid memory leaks.

Summary

watch tracks specific reactive data and runs a callback on changes.

watchEffect runs code immediately and re-runs when any reactive data inside changes.

Both help keep your app reactive and update automatically when data changes.