1.watch侦听器
<template>
第一个值:
<input v-model="msg1" type="text"/><br/>
第二个值:
<input v-model="msg2" type="text"/><br/>
测试深度监听:
<input v-model="person.car.carName" type="text">
</template>
<script setup lang="ts">
import {Ref, ref, watch} from "vue";
const msg1: Ref<string> = ref<string>('')
const msg2: Ref<string> = ref<string>('')
const person = ref({
name: 'Yang',
age: 23,
car: {
carName: 'Mi',
color: 'blue'
}
})
watch(msg1, (newValue, oldValue) => {
console.log('新值=>', newValue)
console.log('旧值=>', oldValue)
})
watch([msg1, msg2], (newValue, oldValue) => {
console.log('新值=>', newValue)
console.log('旧值=>', oldValue)
})
watch(person, (newValue, oldValue) => {
console.log('新值=>', newValue)
console.log('旧值=>', oldValue)
}, {
deep: true,
immediate: true
})
</script>
2.watchEffect 高级侦听器
<template>
<input id="ipt" v-model="msg1" type="text"/><br/>
<input v-model="msg2" type="text"/><br/>
</template>
<script setup lang="ts">
import {ref, watchEffect} from "vue";
let msg1 = ref<string>('hello')
let msg2 = ref<string>('hi')
watchEffect((before) => {
const ipt: HTMLInputElement = document.querySelector('#ipt') as HTMLInputElement
console.log(ipt)
console.log(msg1.value)
console.log(msg2.value)
before(() => {
console.log('先调用这个,在执行其他')
})
}, {
flush: 'post',
onTrigger: (e) => {
debugger
}
})
</script>