In vue3, several common ways to use watch

Without further ado, let’s get straight to the practical code!

First define two variables a, b

import { ref, watch } from 'vue'

const a = ref(0)
const b = ref(0)

1. Monitor each variable individually

watch(() => a.value, (newA, oldA) => {
  console.log(newA, oldA)
})
watch(() => b.value, (newB, oldB) => {
  console.log(newB, oldB)
})

2. Put multiple variables into an array and combine monitoring

watch([a, b], ([newA, newB], [oldA, oldB]) => {
  console.log('newA, oldA:', newA, oldA)
  console.log('newB, oldB:', newB, oldB)
})

3. Put multiple variables into an array and monitor comprehensively

watch([a, b], (newVal, oldVal) => {
  console.log(newVal, oldVal)
}, { immediate: true, deep: true })

In addition, I found through verification that in vue3, if an infinite loop occurs, the variables monitored by watch will only be monitored up to 100 times, thereby avoiding memory/stack overflow problems.

The above content is a summary of my development experience. Any similarity is purely coincidental. In addition, if there are any errors in the content, please point them out in the comment area, thank you!

Guess you like

Origin blog.csdn.net/listener_life/article/details/131043921