watch用来监听特定数据源,并在单独的回调函数中执行副作用。默认是惰性的——即回调仅在侦听源发生变化被调用。
#监听一个getter函数:
const state = reactive({ count: 0 })
watch(
() => state.count,
(newVal, oldVal) => {
//...
}
)
#监听一个ref:
const count = ref(0)
watch(
count,
(newVal, oldVal) => {
//...
}
)
#监听多个数据源:
const foo = ref('')
const bar = ref('')
watch(
[ foo, bar ],
([ newFoo, newBar ], [ oldFoo, oldBar ]) => {
// ...
}
)
#深度监听:
const state = reactive({ count: 0 })
watch(
() => state,
() => {
// ...
},
{ deep: true }
)
// or
watch(state, () => {
// ...
})
错误使用示例:
#错误的使用
watch(props.visible, (newVal) => {
if (newVal) {
xxxx....
}
})
#正确用法 getter ()=>
watch(() => props.visible, (newVal) => {
if (newVal) {
xxxx....
}
})