Home > Article > Web Front-end > How vue3 data monitors watch/watchEffect
We all know that the function of the listener is to trigger every time the responsive state changes. In the combined API, we can use the watch() function and watchEffect() function,
When you change the responsive state, it may trigger Vue component updates and listener callbacks at the same time.
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.
So, let’s take a look, how can we make good use of them? What's the difference between them?
watch needs to listen to a specific data source, such as listening to a ref. The first parameter of watch can be a "data source" in different forms: it can be A ref (including calculated properties), a responsive object, a getter function, or an array of multiple data sources, As follows:
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}`) }) const obj = reactive({ count: 0 }) //传入一个响应式对象 watch(obj, (newValue, oldValue) => { // 在嵌套的属性变更时触发 // 注意:`newValue` 此处和 `oldValue` 是相等的 // 因为它们是同一个对象! }) obj.count++ watch( () => obj.count, (newValue, oldValue) => { // 注意:`newValue` 此处和 `oldValue` 是相等的 // *除非* obj.count 被整个替换了 }, { deep: true } )
Note that you cannot directly listen to the property value of the responsive object
const obj = reactive({ count: 0 }) // 错误,因为 watch() 得到的参数是一个 number watch(obj.count, (count) => { console.log(`count is: ${count}`) })
You need to use a getter function that returns the property:
// 提供一个 getter 函数 watch( () => obj.count, (count) => { console.log(`count is: ${count}`) } )
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 force the listener's callback to execute immediately by passing in the immediate: true option:
watch(source, (newValue, oldValue) => { // 立即执行,且当 `source` 改变时再次执行 }, { immediate: true })
watchEffect( ) allows us to automatically track reactive dependencies of callbacks.
const todoId = ref(1) const data = ref(null) 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, there is no need to specify immediate: true. During execution, it automatically tracks todoId.value as a dependency (similar to a computed property). Whenever todoId.value changes, the callback will be executed again. With watchEffect(), we no longer need to explicitly pass the todoId as the source value .
watchEffect() is suitable for listeners with multiple dependencies. For this example with only one dependency, the benefit is relatively small. 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.
If you want to access the DOM updated by Vue in the listener callback, you need to specify the flush: ‘post’ option,
post-flush watchEffect() There is a more convenient alias watchPostEffect():
import { watchPostEffect } from 'vue' watchPostEffect(() => { /* 在 Vue 更新后执行 */ })
Both watch and watchEffect can execute callbacks with side effects responsively. The main difference between them is how 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 will only be triggered 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, the dependency will be tracked 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. Suitable for listeners with multiple dependencies
The above is the detailed content of How vue3 data monitors watch/watchEffect. For more information, please follow other related articles on the PHP Chinese website!