SoFunction
Updated on 2025-04-04

One article will help you master the use of listeners in vue3

Listener

Both listener and computed properties can be used to listen for changes in responsive data, if needed after the data changes.Perform an action to modify dependencies, then it should be usedListener
watchandwatchEffectAll can listen to data sources and perform callback operations, the difference is how they track responsive dependencies.

watch: Only trace the specified data source, so you can accurately control the triggering timing of the callback function

watchEffect: Automatically track responsive data in the callback, which is more concise than watch, but sometimes its responsive dependencies are less clear.

Watch function

The first parameter needs to specify the data to be listened to.

Can beResponsive data(ref、reactive、computed...)、getter function, it can also be composed of the above data sourceArray, that is, listen to multiple data sources at the same time.

The second parameter is the callback method that needs to be executed when listening for data changes.

The callback method has two parameters, the first is the value after data is updated, and the second is the value before data is updated.

import { ref, watch } from 'vue'
const count = ref(0)
const price = ref(10)
// Listen to responsive datawatch(count, (newVal, oldVal) => {
    // Whenever count is updated, the function here will be executed    ("new count:", newVal) // 1 Updated value    ("old count:", oldVal) // 0 Value before update})
// Listen to getter functionwatch(
    () =>  * ,
    (newVal, oldVal) => {
        // Whenever count or price is updated, the function here will be executed        ("New Total Price:", newVal) // 10 Updated value        ("Old Total Price:", oldVal) // 0 Value before update    })
// Use array to listen to multiple data sourceswatch(
    [count, () => ],
    (newValArr, oldValArr) => {
        // Whenever count or price is updated, the function here will be executed        // It is necessary to note that the callback data at this time is an array        // newValArr[0] count
        // newValArr[1] () => ]
        // oldValArr Same as above        (newValArr) // [1, 10] updated value        (oldValArr) // [0, 10] Value before update    })
++ // renewcountvalue

Optional configuration

The above two parameters are required to be passed in the listener. In addition, there are some optional configurations for the watch function.

Execute now

The default watch will only execute callbacks when the data source is updated. If you want to execute the callback function immediately when it is created, you can pass it inimmediate:trueMake the listener's callback execute immediately

const count = ref(0)
watch(count, (newVal,oldVal) => {
    (newVal)  // 0
    (oldVal)  // undefind
}, {
    immediate: true  // Execute a callback immediately when created})

Deep Listener

Passing a responsive object to the watch function will implicitly create a deep listener - the callback will be triggered during all nested changes:

const obj1 = reactive({ val: 1 })
watch(obj1, (newVal, oldVal) => {
    // Triggered when obj's nested property changes    // Note that the values ​​of newVal oldVal here are equal    // Because they are the same object})
const obj2 = ref({ val: 2 })
// When an object that ref is listened to is passed, adding .value will create deep listening by defaultwatch(, (newVal, oldVal) => {})
++
++

When passing directly into the object created by the ref or a getter function that returns responsive objects, the callback will only be triggered if their objects are replaced entirely. If you want to create deep listening, you can pass it indeep:trueForced to deep listener.

// When passing directly into the object created by ref or returning a getter function that returns a responsive object// Callback will only be triggered if their objects are replaced entirely// Example: = { val: 3 }// Pass in deep option to create deep listening// getter functionwatch(() => , (newVal, oldVal) => {
    // Note that the values ​​of newVal oldVal here are equal    // Unless the entire one is replaced}, {
    deep: true   // Trigger callback when value changes})
// object data created by refwatch(obj2, (newVal, oldVal) => {
    // Note that the values ​​of newVal oldVal here are equal    // Unless the entire one is replaced}, {
    deep: true   // Trigger callback when value changes})

watchEffect function

Like computed properties, there is no need to specify the responsive data to be listened to, but will automatically track the responsive dependencies of the callback and re-execute the callback function when the dependency changes;

And after creation, the callback will be executed immediately (no need to pass immediate:true);

Compared to the watch function, it is more concise and convenient.

import { ref, watchEffect } from 'vue';
const count = ref(0)
watchEffect(() => {
    () // 0
})

Stop listening

When the business requires it, or creates a listener in an asynchronous operation,

The listener can be stopped by the following methods.

const unwatch = watchEffect(() => { })
// Call unwatch() when not needed to destroy the listeningunwatch()
setTimeout(() => {
  // The listener created in synchronization will automatically stop when the component is destroyed, while the one created in asynchronous will not!  watchEffect(() => {})
}, 100)

The callback is triggered after DOM is updated

The data source changes to listen to may trigger vue component updates and listener callbacks at the same time.

By default, the callback will be executed before the component is updated, that is, the dom gets the vue component in the callback.Before the updateThe status of

If you want to access it in the callbackAfter the updateThe state needs to be transmitted toflush: 'post'Options

watch(count, ()=>{
}, {
  flush: 'post'
})
watchEffect(()=>{
}, {
  flush: 'post'
})

Note

Callback parameters of watch function

There are two parameters of the callback function, the first one is "new value" and the second one is "old value". If you only need to use "new value", you can ignore the second value.

If the data being listened to is an object, their "new value" is equal to the "old value" because they both point to the same memory address unless the entire one is replaced.

Try not to create listening in asynchronous

Try not to create listening in asynchronous. Listening created in asynchronous will not be automatically destroyed. If you create listening in asynchronous, please end the listening manually.

This is the article about this article that will help you master the use of listeners in vue3. For more related contents of vue3 listeners, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!