SoFunction
Updated on 2025-04-05

Example code for vue3 data monitoring watch/watchEffect

We all know that the listener functions in every responsive stateWhen changes occurTrigger, in the combined API, we can usewatch() functionandwatchEffect() function,

When you change the responsive state, it may trigger both Vue component updates and listener callbacks.

By default, user-created listener callbacks will be called before the Vue component is updated. This means that the DOM you accessed in the listener callback will be in the state before it was updated by Vue.

So, let’s take a look at how to use them well? What is the difference between them?

watch() function

Watch needs to listen for a specific data source, such as listening for a ref, the first parameter of the watch can be a different form of "data source": it can be aref(including computed attributes), aResponsive Objects,onegetter function,orArray of multiple data sources,as follows:

const x = ref(0)
const y = ref(0)

// Single refwatch(x, (newX) => {
  (`x is ${newX}`)
})

// getter functionwatch(
  () =>  + ,
  (sum) => {
    (`sum of x + y is: ${sum}`)
  }
)



// Array of multiple sourceswatch([x, () => ], ([newX, newY]) => {
  (`x is ${newX} and y is ${newY}`)
})


const obj = reactive({ count: 0 })
//Passing in a responsive objectwatch(obj, (newValue, oldValue) => {
  // Triggered when nested property changes  // Note: `newValue` is equal here and `oldValue`  // Because they are the same object!})

++


watch(
  () => ,
  (newValue, oldValue) => {
    // Note: `newValue` is equal here and `oldValue`    // *Unless * is replaced by the entire  },
  { deep: true }
)

Note that you cannot directly listen for the property values ​​of responsive objects.

const obj = reactive({ count: 0 })

// Error, because the parameter obtained by watch() is a numberwatch(, (count) => {
  (`count is: ${count}`)
})

Here you need to use a return to this propertygetter function

// Provide a getter functionwatch(
  () => ,
  (count) => {
    (`count is: ${count}`)
  }
)

Watch is lazy to execute by default: callbacks are executed only if the data source changes. But in some scenarios, we want to execute the callback immediately when creating the listener. For example, we want to request some initial data and then re-request the data when the relevant state changes.

We can pass inimmediate: trueOption to force the listener's callback to execute immediately:

watch(source, (newValue, oldValue) => {
  // Execute immediately and execute again when `source` changes}, { immediate: true })

watchEffect() function

watchEffect() allows usAutomatic trackingResponsive dependency of callbacks.

const todoId = ref(1)
const data = ref(null)

watchEffect(async () => {
  const response = await fetch(
    `/todos/${}`
  )
   = await ()
})

In this example, the callback will be executed immediately.No need to specify immediate: true. During execution, it is automatically traced as a dependency (similar to computed properties). Whenever a change occurs, the callback is executed again. With watchEffect(), weNo need to explicitly pass todoId as source value

watchEffect() is suitable for listeners with multiple dependencies. For examples where there is only one dependency, the benefits are relatively small. Additionally, if you need to listen for several properties in a nested data structure, watchEffect() may be more efficient than a depth listener, because it will track only the properties used in the callback, rather than recursively track all properties.

If you want to access the DOM updated by Vue in the listener callback, you need to specifyflush: ‘post’Options,
The post-refresh watchEffect() has a more convenient alias watchPostEffect():

import { watchPostEffect } from 'vue'

watchPostEffect(() => {
  /* Execute after Vue update */
})

The connection and difference between watch and watchEffect

Both watch and watchEffect can responsively execute callbacks with side effects. The main difference between them isHow to track responsive dependencies

Watch only trackingDefinitely listen to the data source. It won't track anything accessed in the callback. in addition,Callbacks are triggered only if the data source does change. Watch avoids tracking dependencies when side effects occur, so we can control the triggering timing of the callback function with more precise accuracy.

watchEffect will track dependencies during side effects. It automatically tracks all accessible responsive properties during synchronous execution. This is more convenient, and the code tends to be more concise, but sometimes its responsive dependencies are less explicit.Suitable for listeners with multiple dependencies

This is the article about how vue3 monitors watch/watchEffect. For more related vue3 data monitoring watch/watchEffect, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!