watch
- 和Vue2基本相似,配置是一样的
- 两个坑:
- 监视reactive定义的响应式数据时:oldVal无法正确的获取,强制开启了深度监视(deep配置无效)
- 监视reactive定义的响应式数据中的某个属性(对象)时:deep配置有效
<template>
<h1>{{num}}</h>
<h1>{{msg}}</h>
</template>
<script>
import {ref,reactive,watch} from 'vue'
exprot default {
name: 'App',
setup() {
let num = ref(0)
let msg= ref('消息')
let p = reactive({
name: '景天',
age: 18,
a: {
b: {
c: 100
}
}
})
watch(num,(newVal,oldVal)=> {
console.log(newVal,oldVal)
},{immediate:true})
watch([num,msg],(newVal,oldVal)=> {
console.log(newVal,oldVal)
},{immediate:true})
watch(p,(newVal,oldVal)=> {
console.log(newVal,oldVal)
},{deep:false})
watch(()=>p.name,(newVal,oldVal)=> {
console.log(newVal,oldVal)
})
watch([()=>p.name,()=>p.age],(newVal,oldVal)=> {
console.log(newVal,oldVal)
},{deep:false})
watch(()=>p.a,(newVal,oldVal)=> {
console.log(newVal,oldVal)
},{deep:true})
return {
num,
msg,
p
}
}
}
</script>