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

HTML table tag tutorial (31): cell width and height attributes WIDTH, HEIGHT

By default, the width and height of the cell are ...

Alibaba Cloud Server Domain Name Resolution Steps (Tutorial for Beginners)

For novices who have just started to build a webs...

Solution to failure in connecting to mysql in docker

Scenario: After installing the latest version of ...

SQL fuzzy query report: ORA-00909: invalid number of parameters solution

When using Oracle database for fuzzy query, The c...

Examples of optimistic locking and pessimistic locking in MySQL

The task of concurrency control in a database man...

Installation process of zabbix-agent on Kylin V10

1. Download the installation package Download add...

How to optimize images to improve website performance

Table of contents Overview What is Image Compress...

MySQL 5.7.24 installation and configuration graphic tutorial

This article shares the installation and configur...

How to enable MySQL remote connection

For security reasons, MySql-Server only allows th...

Use js to call js functions in iframe pages

Recently, I have been working on thesis proposals ...

Practical tutorial on modifying MySQL character set

Preface: In MySQL, the system supports many chara...