watch 监听 ref 类型
setup() {
let val = ref(1);
watch(val,(newValue, oldValue)=>{
console.log(`原值为${oldValue}`)
console.log(`新值为${newValue}`)
})
setTimeout(() => {
val.value ++
}, 1000)
}
watch 监听 reactive 类型
setup() {
const obj = reactive({count: 1})
watch(() => obj.count, (newValue, oldValue) => {
console.log(`原值为${oldValue}`)
console.log(`新值为${newValue}`)
})
setTimeout(() => {
obj.count ++
}, 1000)
}
watchEffect
setup() {
const obj = reactive({ name: 'jf', count: 1 })
watchEffect(() => {
console.log(obj.name)
console.log(obj.count)
})
setTimeout(() => {
obj.name = '117'
obj.count ++
}, 1000)
}
watchEffect 与 watch 的区别主要有以下几点:
- watchEffect不需要手动传入依赖
- watchEffect每次初始化时会执行一次回调函数来自动获取依赖
- watchEffect无法获取到原值,只能得到变化后的值