【vue3】Usage of watch listener

Computed properties allow us to declaratively calculate derived values. However, in some cases, we need to perform some "side effects" when the state changes: such as changing the DOM, or modifying the state of another place based on the results of an asynchronous operation.

In the composite API, we can use the watch function to trigger a callback function every time the reactive state changes :

<script setup>
import {
      
       ref, watch } from 'vue'

const question = ref('')
const answer = ref('Questions usually contain a question mark. ;-)')

// 可以直接侦听一个 ref
watch(question, async (newQuestion, oldQuestion) => {
      
      
  if (newQuestion.indexOf('?') > -1) {
      
      
    answer.value = 'Thinking...'
    try {
      
      
      const res = await fetch('https://yesno.wtf/api')
      answer.value = (await res.json()).answer
    } catch (error) {
      
      
      answer.value = 'Error! Could not reach the API. ' + error
    }
  }
})
</script>

<template>
  <p>
    Ask a yes/no question:
    <input v-model="question" />
  </p>
  <p>{
   
   { answer }}</p>
</template>

Try it out on the training ground

Listening data source type

The first parameter of watch can be a "data source" in different forms: it can be a ref (including calculated properties), a reactive object, a getter function, or an array of multiple data sources:

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

// 单个 ref
watch(x, (newX) => {
    
    
  console.log(`x is ${
      
      newX}`)
})

// getter 函数
watch(
  () => x.value + y.value,
  (sum) => {
    
    
    console.log(`sum of x + y is: ${
      
      sum}`)
  }
)

// 多个来源组成的数组
watch([x, () => y.value], ([newX, newY]) => {
    
    
  console.log(`x is ${
      
      newX} and y is ${
      
      newY}`)
})

Note that you cannot directly listen to the property value of a reactive object, for example:

const obj = reactive({
    
     count: 0 })

// 错误,因为 watch() 得到的参数是一个 number
watch(obj.count, (count) => {
    
    
  console.log(`count is: ${
      
      count}`)
})

Here you need to use a getter function that returns the property:

// 提供一个 getter 函数
watch(
  () => obj.count,
  (count) => {
    
    
    console.log(`count is: ${
      
      count}`)
  }
)

deep listener

Passing a reactive object directly to watch() will implicitly create a deep listener - this callback function will be triggered on all nested changes:

const obj = reactive({
    
     count: 0 })

watch(obj, (newValue, oldValue) => {
    
    
  // 在嵌套的属性变更时触发
  // 注意:`newValue` 此处和 `oldValue` 是相等的
  // 因为它们是同一个对象!
})

obj.count++

In contrast, a getter function that returns a reactive object will only trigger a callback if it returns a different object:

watch(
  () => state.someObject,
  () => {
    
    
    // 仅当 state.someObject 被替换时触发
  }
)

You can also explicitly add the deep option to the above example to force it to be a deep listener:

watch(
  () => state.someObject,
  (newValue, oldValue) => {
    
    
    // 注意:`newValue` 此处和 `oldValue` 是相等的
    // *除非* state.someObject 被整个替换了
  },
  {
    
     deep: true }
)

Use with caution

Deep listening requires traversing all nested properties in the object being listened to, which is very expensive when used for large data structures. So use it only when necessary and keep an eye on performance.

Listener for immediate callback

Watch is lazy by default: the callback will only be executed when 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 immediate: trueforce the listener's callback to execute immediately by passing in the option:

watch(source, (newValue, oldValue) => {
    
    
  // 立即执行,且当 `source` 改变时再次执行
}, {
    
     immediate: true })

watchEffect()

It's common for a listener's callback to use the exact same reactive state as the source. For example, the following code uses a listener to load a remote resource whenever the reference to todoId changes:

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

watch(todoId, async () => {
    
    
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/todos/${
      
      todoId.value}`
  )
  data.value = await response.json()
}, {
    
     immediate: true })

In particular, notice how the listener is used twice todoId, once as the source and once in the callback.

We can use the watchEffect function to simplify the above code. watchEffect() allows us to automatically track reactive dependencies of callbacks. The listener above can be rewritten as:

watchEffect(async () => {
    
    
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/todos/${
      
      todoId.value}`
  )
  data.value = await response.json()
})

In this example, the callback will be executed immediately, and there is no need to specify immediate: true. During execution, it automatically tracks todoId.value as a dependency (similar to computed properties). Whenever todoId.value changes, the callback will be executed again. With watchEffect(), we no longer need to explicitly pass todoId as the source value.

For an example like this with only one dependency, the benefit of watchEffect() is relatively small. But for listeners with multiple dependencies, using watchEffect() removes the burden of manually maintaining the dependency list. Additionally, if you need to listen to several properties in a nested data structure, watchEffect() may be more efficient than a deep listener, since it will only track the properties that are used in the callback, rather than recursively tracking all properties.

TIP
watchEffect only tracks dependencies during its synchronous execution. When using asynchronous callbacks, only properties accessed before the first await works properly will be tracked.

watch vs. watchEffect

Both watch and watchEffect can reactively execute callbacks with side effects. The main difference between them is the way reactive dependencies are tracked:

watch only tracks data sources that are explicitly listened to. It won't track anything accessed in the callback. Additionally, the callback is only fired when the data source actually changes. watch avoids tracking dependencies when side effects occur, so we can more precisely control when the callback function is triggered.

watchEffect will track dependencies during the occurrence of side effects. It will automatically track all accessible reactive properties during synchronization. This is more convenient and the code tends to be cleaner, but sometimes its reactive dependencies are less clear.

The triggering time of the callback

When you change reactive 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 access in the listener callback will be the state it was in before it was updated by Vue.

If you want to be able to access the DOM after being updated by Vue in the listener callback, you need to specify the flush: 'post' option:

watch(source, callback, {
    
    
  flush: 'post'
})

watchEffect(callback, {
    
    
  flush: 'post'
})

Post-refresh watchEffect() has a more convenient alias watchPostEffect():

import {
    
     watchPostEffect } from 'vue'

watchPostEffect(() => {
    
    
  /* 在 Vue 更新后执行 */
})

Stop listener

<script setup>Listeners created with synchronization statements in setup() or will be automatically bound to the host component instance and will automatically stop when the host component is uninstalled. Therefore, in most cases you don't need to worry about stopping a listener.

A key point is that the listener must be created with a synchronous statement: if you create a listener with an asynchronous callback, then it will not be bound to the current component and you must stop it manually to prevent memory leaks. Such as the following example:

<script setup>
import {
    
     watchEffect } from 'vue'

// 它会自动停止
watchEffect(() => {
    
    })

// ...这个则不会!
setTimeout(() => {
    
    
  watchEffect(() => {
    
    })
}, 100)
</script>

To manually stop a listener, call the function returned by watch or watchEffect:

const unwatch = watchEffect(() => {
    
    })

// ...当该侦听器不再需要时
unwatch()

Note that there are few situations where you need to create a listener asynchronously. Please choose to create it synchronously whenever possible. If you need to wait for some asynchronous data, you can use conditional listening logic:

// 需要异步请求得到的数据
const data = ref(null)

watchEffect(() => {
    
    
  if (data.value) {
    
    
    // 数据加载后执行某些操作...
  }
})

Guess you like

Origin blog.csdn.net/weixin_43361722/article/details/129888215