Middle
What is the difference between watch and watchEffect?
sobes.tech AI
Answer from AI
watch and watchEffect are reactive functions in Vue.js that allow tracking changes in reactive data, but they work slightly differently:
-
watch: used to observe specific reactive sources (variables, computed properties). It allows performing side effects when these data change. You can access the old and new values.
watch(() => someRef.value, (newVal, oldVal) => { console.log(`Changed from ${oldVal} to ${newVal}`); }); -
watchEffect: automatically tracks all reactive dependencies used inside the passed function and reruns it when they change. It does not provide access to old values.
watchEffect(() => { console.log(`Current value is ${someRef.value}`); });
In summary:
watch— more explicit and precise control over specific sources.watchEffect— convenient for automatically tracking all reactive dependencies inside a function.