The role of the watchEffect function:
A function passed in, when the dependency changes, re-execute the changed function.
watchEffect function features:
Similar to watch, it can monitor a data source.
But watchEffect will be called once during initialization, similar to immediate of watch.
watchEffect uses
watchEffect(() => {
console.log(`当${
sum.person.age}的值变化的时候调用,初始化
的时候也调用一次
`)
}) //打印结果
//18 的值变化了!初始化调用
//19 的值变化了依赖项调用
watchEffect accepts a side effect function
watchEffect(onInvalidate => {
console.log(`${
sum.person.age} 的值变化了!`)
onInvalidate(() => {
console.log('清除副作用函数执行了!')
})
}) //打印结果
//18 的值变化了!
//清除副作用函数执行了!
//19 的值变化了!
Notes on onInvalidate clear side effect function
1.该函数总是在watchEffect执行的时候再次执行
2.当组件被销毁的时候该函数再次执行
3.该函数总是优先于watchEffect中的同步/异步代码执行
4.Promize函数的执行应该在该函数下面
The execution timing of onInvalidate to clear the side effect function is controlled by flush
watchEffect(onInvalidate => {
console.log(`${
sum.person.age} 的值变化了!`)
onInvalidate(() => {
console.log('清除函数执行了!')
})
},{
//'pre' 在组件更新更新前运行,默认为'pre'
//'post'在组件更新更新后运行
//'sync'强制效果始终同步触发。然而,这是低效的,应该很少需要。
flush:'post'
})//打印结果
//18 的值变化了!
//清除函数执行了!
// 19 的值变化了!
watchEffect listener debug
watchEffect(() => {
console.log(`${
sum.person.age} 的值变化了!`)
}, {
onTrack(e) {
//追踪其依赖的时候触发,只能在开发者模式下使用
console.log(e.target)
},
onTrigger(e) {
//依赖项被改变的时候触发,只能在开发者模式下使用
console.log(e.target)
}
})
watchPostEffect
Alias for watchEffect with flush: 'post' option.
watchSyncEffect
Alias for watchEffect with flush: 'sync' option.
#watch