A brief analysis of the use of watchEffect in Vue3

A brief analysis of the use of watchEffect in Vue3

Preface

Everyone should be familiar with the watch api in vue2. There is a $watch method in the vue instance in vue2 and a watch option in sfc (sign file component). It can be used to execute the desired behavior when a property changes. for example:

  • When the ID changes, get the new data from the database.
  • Perform an animation when a property changes.
  • When the search conditions change, update the queried data.

But in addition to the watch api, vue3 also added a watchEffect api. Let's take a look at its usage.

We collect a dependency on userID, and then when userID changes, the watchEffect callback is executed.

// Example inspired by the [documentation](https://v3.vuejs.org/api/computed-watch-api.html#watcheffect)

import { watchEffect, ref } from 'vue'
setup () {
    const userID = ref(0)
    watchEffect(() => console.log(userID))
    setTimeout(() => {
      userID.value = 1
    }, 1000)

    /*
      * LOG
      * 0 
      * 1
    */

    return {
      userID
    }
 }

How is it different from watch?

  • First, we can see from the sample code that watchEffect does not need to specify the properties to be monitored. It will automatically collect dependencies. As long as we reference the responsive properties in the callback, when these properties change, the callback will be executed, while watch can only monitor the specified properties and make changes (starting from v3, multiple properties can be specified at the same time).
  • The second point is that watch can get the new value and the old value (the value before the update), but watchEffect cannot.
  • The third point is that if watchEffect exists, it will be executed once when the component is initialized to collect dependencies (similar to computed), and then the collected dependencies will change, the callback will be executed again, and watch does not need it because it specifies the dependencies at the beginning.

From their differences we can see their advantages and disadvantages. And you can make the right choice based on business needs.

watchEffect Advanced

Stop monitoring

watchEffect returns a function to stop the listener, as follows:

const stop = watchEffect(() => {
  /* ... */
})

// later
stop()

The examples come from the official documentation, which is linked above.

If watchEffect is registered in setup or lifecycle, it will automatically stop when the component is unmounted.

Disable the side effect

What is a side effect? ​​Unpredictable interface requests are a side effect. Suppose we use a user ID to query user details, and then we monitor the user ID. When the user ID changes, we will initiate a request. This is very simple and can be done with a watch. However, if our user ID changes multiple times during the data request process, we will make multiple requests, and the last returned data will overwrite all the user details we returned previously. This not only leads to a waste of resources, but also fails to guarantee the order in which the watch callbacks are executed. And using watchEffect we can do it.

onInvalidate()

The callback passed in to onInvalidate(fn) will be executed when watchEffect is rerun or watchEffect is stopped

watchEffect(() => {
      // Asynchronous API call, returns an operation object const apiCall = someAsyncMethod(props.userID)

      onInvalidate(() => {
        // Cancel the asynchronous API call.
        apiCall.cancel()
      })
})

With the help of onInvalidate, we can make a more elegant optimization for the situation described above.

Summarize

This is the end of this article about the use of watchEffect in Vue3. For more information about the use of Vue3 watchEffect, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • The use and difference between vue3 watch and watchEffect
  • Detailed explanation of the usage of watch and watchEffect in VUE3
  • Do you know about watch and watchEffect of vue3?
  • A brief discussion on the specific usage of watchEffect in Vue3
  • Detailed examples of watch and watchEffect in vue3

<<:  Detailed explanation of screen command usage in Linux

>>:  Share some key interview questions about MySQL index

Recommend

11 common CSS tips and experience collection

1. How do I remove the blank space of a few pixels...

A complete guide to some uncommon but useful CSS attribute operations

1. Custom text selection ::selection { background...

jQuery clicks on the love effect

This article shares the specific code of jQuery&#...

CSS3 countdown effect

Achieve results Implementation Code html <div ...

A detailed discussion of MySQL deadlock and logs

Recently, several data anomalies have occurred in...

Parsing MySQL binlog

Table of contents 1. Introduction to binlog 2. Bi...

Docker learning method steps to build ActiveMQ message service

Preface ActiveMQ is the most popular and powerful...

CSS code for arranging photos in Moments

First, you can open Moments and observe several l...

MySQL 5.7 Common Data Types

——Notes from "MySQL in Simple Terms (Second ...

Detailed tutorial on installing the jenkins container in a docker environment

Recommended Docker learning materials: https://ww...

AsyncHooks asynchronous life cycle in Node8

Async Hooks is a new feature of Node8. It provide...

Example of how to enable Brotli compression algorithm for Nginx

Brotli is a new data format that can provide a co...