In Vue, watch and watchEffect are two reactive watchers capable of responding to changes in reactive state, but they operate differently and are suited for distinct use cases.
watch
The watch API allows you to listen to specific data sources and execute callback functions when the source changes. It is part of the reactivity system and is ideal for performing asynchronous operations or expensive computations because you can precisely control when and how to respond to state changes.
- Precision:
watchenables you to specify exact reactive references or computed properties to monitor. - Lazy Execution:
watchdoes not execute the callback immediately by default; it only triggers when the watched reactive source changes. - Deep Watching:
watchcan be configured for deep watching, tracking changes to internal properties of objects. - Old and New Values: The
watchcallback provides both new and old values for easy comparison. - Stopping Watching:
watchreturns a stop function that you can use to halt listening.
Example:
vue<template> <div>{{ count }}</div> </template> <script> export default { data() { return { count: 0 } }, watch: { count(newVal, oldVal) { // When count changes, this function is called console.log(`Count changed from ${oldVal} to ${newVal}`); } } } </script>
watchEffect
watchEffect is a reactive watcher that automatically tracks all reactive states used within its function and re-executes the function when these states change.
- Automatic Tracking:
watchEffectautomatically monitors all reactive references within the function and re-runs when they update. - Immediate Execution:
watchEffectexecutes immediately upon creation to synchronize the reactive effect with the current state. - Automatic Dependency Collection: Unlike
watch, you don't need to specify the exact state to monitor; it collects dependencies automatically. - No Old Values:
watchEffectdoes not provide old values since it does not target specific data sources. - Stopping Watching:
watchEffectalso returns a stop function to cease listening.
Example:
vue<template> <div>{{ count }}</div> </template> <script> import { ref, watchEffect } from 'vue'; export default { setup() { const count = ref(0); watchEffect(() => { // This function executes immediately when setup() is called and again when count changes console.log(`Count is now: ${count.value}`); }); return { count }; } } </script>
In summary, use watch when you need to monitor specific data and perform comparisons or execute complex logic upon changes, whereas use watchEffect when you want to automatically track and respond to reactive state changes without excessive control over the watch source or execution timing.