乐闻世界logo
搜索文章和话题

What is the difference between watch and watchEffect in Vue?

2024年6月24日 16:43

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: watch enables you to specify exact reactive references or computed properties to monitor.
  • Lazy Execution: watch does not execute the callback immediately by default; it only triggers when the watched reactive source changes.
  • Deep Watching: watch can be configured for deep watching, tracking changes to internal properties of objects.
  • Old and New Values: The watch callback provides both new and old values for easy comparison.
  • Stopping Watching: watch returns 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: watchEffect automatically monitors all reactive references within the function and re-runs when they update.
  • Immediate Execution: watchEffect executes 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: watchEffect does not provide old values since it does not target specific data sources.
  • Stopping Watching: watchEffect also 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.

标签:前端Vue