Home >Web Front-end >Vue.js >Learn about watchEffect in Vue3 in one article and talk about its application scenarios!

Learn about watchEffect in Vue3 in one article and talk about its application scenarios!

青灯夜游
青灯夜游forward
2022-05-06 18:56:267300browse

This article will take you to understand watchEffect in Vue3, introduce its side effects, and talk about what it can do. I hope it will be helpful to everyone!

Learn about watchEffect in Vue3 in one article and talk about its application scenarios!

watchEffect, which immediately executes a function passed in while reactively tracking its dependencies and re-running the function when its dependencies change. (Learning video sharing: vue video tutorial)

In other words: watchEffect is equivalent to merging the dependency source and callback function of watch, This callback function is re-executed when any of your reactive dependencies are updated. Different from watch, the callback function of watchEffect will be executed immediately (i.e. { immediate: true })

This article mainly describes how to use Clear side effectsMake our code more elegant~

watchEffect's side effects

What are side effects (side effect), Simply put, a side effect is to perform a certain operation, such as modification of external variable data or variables, call of external interface, etc. The callback function of watchEffect is a side effect function, because we use watchEffect to perform certain operations after listening to changes in dependencies.

When a side effect function is executed, it will inevitably have some impact on the system. For example, a timer setInterval is executed in the side effect function, so we must deal with the side effects. Vue3watchEffectThe function that listens for side effects can receive an onInvalidate function as an input parameter to register a callback when the cleanup fails. This invalidation callback will be triggered when the following situations occur:

  • The side effect is about to be re-executed (that is, the value of the dependency changes)
  • The listener is stopped (returned by the explicit call The value stops listening, or the component is uninstalled and the stop listening is called implicitly)
import { watchEffect, ref } from 'vue'

const count = ref(0)
watchEffect((onInvalidate) => {
  console.log(count.value)
  onInvalidate(() => {
    console.log('执行了onInvalidate')
  })
})

setTimeout(()=> {
  count.value++
}, 1000)

The order in which the above code is printed is: 0 -> Executed onInvalidate, and finally execute -> 1

Analysis: During initialization, the value of count is first printed 0, and then due to the timer Update the value of count to 1. At this time, the side effect will be executed again, so the callback function of onInvalidate will be triggered and executed onInvalidate# will be printed. ##, and then executes the side effect function and prints the value 1 of count.

import { watchEffect, ref } from 'vue'

const count = ref(0)
const stop = watchEffect((onInvalidate) => {
  console.log(count.value)
  onInvalidate(() => {
    console.log('执行了onInvalidate')
  })
})

setTimeout(()=> {
  stop()
}, 1000)

The above code: When we display the

stop function to stop listening, the onInvalidate callback function will also be triggered. Similarly, when the component where watchEffect is located will implicitly call the stop function to stop listening, so the callback of onInvalidate can also be triggered. function.

watchEffect application

Using the non-lazy execution of

watchEffect and the passed in onInvalidate function, we can do What happened?

Scenario 1: Usually we define a timer or listen for an event. We need to define or register it in the mounted life cycle hook function, and then the component is destroyed Previously, the timer was cleared or the listening function was cleared in the beforeUnmount hook function. In this way, our logic is scattered in two life cycles, which is not conducive to maintenance and reading.

If I use

watchEffect, the creation and destruction logic are put together, and the code is more elegant and easy to read~

// 定时器注册和销毁
watchEffect((onInvalidate) => {
  const timer = setInterval(()=> {
    // ...
  }, 1000)
  onInvalidate(() => clearInterval(timer))
})

const handleClick = () => {
 // ...
}
// dom的监听和取消监听
onMounted(()=>{
  watchEffect((onInvalidate) => {
    document.querySelector('.btn').addEventListener('click', handleClick, false)
    onInvalidate(() => document.querySelector('.btn').removeEventListener('click', handleClick))
  })
})

Scenario 2: Use watchEffect to make an anti-shake throttling (such as canceling a request)

const id = ref(13)
watchEffect(onInvalidate => {
   // 异步请求
  const token = performAsyncOperation(id.value)
  // 如果id频繁改变,会触发失效函数,取消之前的接口请求
  onInvalidate(() => {
    // id has changed or watcher is stopped.
    // invalidate previously pending async operation
    token.cancel()
  })
})

......

Of course

watchEffect can also do many things, such as opening a modification In the modal pop-up window, if a change in id is detected, we can reset the initial parameters in the onInvalidate function... This is just an introduction, I hope everyone will discover more~

(Learning video sharing:

web front-end development, Basic programming video)

The above is the detailed content of Learn about watchEffect in Vue3 in one article and talk about its application scenarios!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete