主要结构
import {ref, reactive,watch} from 'vue'
watch([监听值1,监听2,...],(newVal,oldVal)=>{
...
},{
deep:true,
immediate:true,
flush:'pre'
)
具体写法
<template>
<div>
case1:<input v-model="name"/>
</div>
<div>
case2:<input v-model="name2"/>
</div>
<div>
深度监听:<input v-model="deep.child.inner.num"/><br>
深度监听单个属性:<input v-model="deep2.child.name"/>
</div>
</template>
<script setup lang='ts'>
import {ref, reactive,watch} from 'vue'
let name = ref<string>('youyunxia')
let name2 = ref<string>('张三')
watch(name,(newVal,oldVal)=>{
console.log(newVal,oldVal)
})
watch([name,name2],(newVal,oldVal)=>{
console.log(newVal,oldVal)
})
let deep = reactive({
name:'youyunxia',
child:{
name:'child',
inner:{
num:3
}
}
})
watch(deep,(newVal,oldVal)=>{
console.log(newVal,oldVal)
},{
deep:true,
immediate:true,
flush:'pre'
})
let deep2 = reactive({
child:{
name:'child',
inner:{
num:3
}
}
})
watch( ()=> deep2.child.name,(newVal,oldValue)=>{
console.log(newVal,oldValue)
})
</script>
<style>
</style>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80