Watch and watchEffect help you react to changes in data automatically. They run code when something you care about changes.
Watch and watchEffect in 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.
watch(() => count.value, (newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`);
});watch([() => firstName.value, () => lastName.value], ([newFirst, newLast], [oldFirst, oldLast]) => {
console.log(`Name changed from ${oldFirst} ${oldLast} to ${newFirst} ${newLast}`);
});count changes.watchEffect(() => {
console.log(`Count is now ${count.value}`);
});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.
<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>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.
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.