1.watch的防抖实战
<template>
<div>
<input type="text" v-model="num" id="">
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
type timers = null | number
let num = ref(20)
let timer:timers= null
watch(num,(newValue)=>{
if (timer!==null) {
clearTimeout(timer)
}
timer = setTimeout(() => {
console.log(newValue);
}, 400);
},{
immediate:true
})
</script>
<style scoped lang="less">
</style>
2.watch的监听,watchEffect的实战
<template>
<div>
<span>{{ num }}</span>
<button @click="num++">点我+1</button>
<hr />
<h2>当前的信息:{{ msg }}</h2>
<button @click="msg += '!!'">你好吗</button>
<hr />
<h2>姓名:{{ person.name }}</h2>
<h2>年龄: {{ person.age }}</h2>
<h2>薪水:{{ person.job.job1.salary }}</h2>
<button @click="person.name += '6'">给我变6</button>
<button @click="person.age++">给我变老</button>
<button @click="person.job.job1.salary++">加钱</button>
</div>
</template>
<script setup lang="ts">
import { ref, watch, reactive, watchEffect } from "vue";
let num = ref(0);
let msg = ref("你好呀");
let person = reactive({
name: "张三",
age: 18,
job: {
job1: {
salary: 20,
},
},
});
watch(
num,
(newValue, oldValue) => {
console.log("num正在变化", newValue, oldValue);
},
{ immediate: true, deep: true }
);
watchEffect(() => {
const x1 = person.name;
console.log(x1);
});
watch([num,msg], (newValue, oldValue) => {
console.log("num正在变化", newValue, oldValue);
});
watch(person,(newValue,oldValue) => {
console.log('person变化了',newValue,oldValue);
})
watch(()=>person.name, (newValue, oldValue) => {
console.log("person变化了", newValue, oldValue);
});
watch(
() => person.job,
(newValue, oldValue) => {
console.log("person变化了", newValue, oldValue);
},
{ deep: true }
);
</script>
<style scoped lang="less"></style>