Detailed explanation of watch and watchEffect in Vue3
Using watch and watchEffect in vue 3 componentized development requires import
import { watch, watchEffect } from 'vue'
watch
Attributes
- watch has a certain inertia
- You can get the original value and the current value
- Can listen to the transformation of multiple data, carried by a listener
pass parameters
- The first parameter, you need to pass a function, ref, reactive object that needs to be monitored
- The second parameter is used to accept the original value and current value of the data
- The third parameter, pass advanced configuration items of watch such as immediate: true
First, the basic type of monitoring
const count = ref(0) watch(count, (newValue, oldValue) => { console.log('watch' + newValue, oldValue) })
Second, monitor complex types
In actual development, we often need to monitor a complex type, which is written as follows
const boy = reactive({ name: '小小孩子们', blog: 'www.xxhzm.cn', friend: { friend1 : '小明', friend2 : '小红' } })
-
listen to the whole object
watch(boy, (newValue, oldValue) => { console.log('boy发生了变化') console.log(newValue); console.log(newValue.friend); }) boy.name = 'Little children' boy.friend.friend3 = '小王'
The first parameter is passed into the object we want to monitor. When any property in the monitored object changes, the watch method will be triggered.
-
Listen to a property in an object
// 如果我们直接写boy.name watch(boy.name, (newValue, oldValue) => { console.log('boy发生了变化') console.log(newValue) }) // vue会提示我们,监听的对象需要是一个function 或者ref 或者是一个reactive object // 正确的写法是: watch(() => boy.name, (newValue, oldValue) => { console.log('boy发生了变化') console.log(newValue) }) boy.name = 'Little children'
-
All properties of the listener object
watch(() => boy, (newValue, oldValue) => { console.log('boy发生了变化') console.log(newValue) }, { immediate: true }) boy.name = 'Little children'
-
Monitor multiple data
watch can receive an array inside
No matter which data in the array changes, the listener will be executed
watch([()=> boy.name, count], ([newName, newCount], [oldName, oldCount]) => { console.log(newName + '---' + oldName) console.log(newCount + '---' + oldCount) }) boy.name = 'Little children'
watchEffect
Attributes
- Immediate execution, no laziness
- No need to pass the content to be listened to, it will automatically sense code dependencies, no need to pass many parameters, just a callback function
- Cannot get the value of the previous data
First, the basic type of monitoring
const count = ref(0) watchEffect(() => { console.log(count.value) }) count.value ++
This article is reprinted from https://www.xxhzm.cn/archives/651/
This site is for inclusion only, and the copyright belongs to the original author.