1、watch
1.1基本使用
作用:數據監聽
語法:
watch(監聽的數據, (改變后的數據, 改變前的數據) => {
console.log(newVal, oldVal);
})
注意點:watch寫法上支持一個或者多個監聽源,這些監聽源必須只能是getter/effect
函數,ref數據,reactive對象,或者是數組類型
<template><div><h1>watch</h1><p>name: {{ name }} <button @click="btn">修改名字</button></p><p><input type="text" v-model="code" /> {{ code }}</p></div>
</template><script setup>
import { ref,reactive,toRefs, watch } from 'vue';// 定義變量let name=ref('張三')const btn=()=>{name.value='李四'}// 監聽單個數據watch(name,(newVal,oldVal)=>{// 李四 張三console.log(newVal,oldVal);})// 定義對象let res=reactive({code:200,data:[],massge:'ok'})const {code}=toRefs(res)// 監聽對象watch(()=>res.code,(newVal,oldVal)=>{// 2001 200console.log(newVal,oldVal);})// 監聽多個數據watch([name,()=>res.code],(newVal,oldVal)=>{//['張三', '2001'] ['張三', 200]console.log(newVal,oldVal);})
</script>
1.2、深度監聽、立即監聽
關鍵字:
deep:true 深度監聽
immediate:true 立即監聽
<template><div><h1>watch</h1><p><input type="text" v-model="res.user.name" /> {{ res.user.name }}</p></div>
</template><script setup>
import { ref,reactive,toRefs, watch } from 'vue';// 定義對象let res=reactive({user:{name:'張三'}})// 監聽多個數據watch(()=>res.user,(newVal,oldVal)=>{console.log(newVal,oldVal);},{deep:true,immediate:true})
</script>
2、watchEffect
watchEffect用來簡化 watch,不需要指定監聽對象
而是根據函數內的依賴,用到了什么 當它發生變化時,自動觸發
watchEffect回調會立即執行 不需要指定immediate
<template><div><h1>watchEffect</h1><p><input type="text" v-model.number="num1"><input type="text" v-model.number="num2"></p></div></template><script setup>import { ref,watchEffect } from 'vue';let num1=ref(0);let num2=ref(1);watchEffect(()=>{console.log(num1.value+num2.value);console.log('執行啦watchEffect');})</script>
對比點 | watch | watchEffect |
---|---|---|
惰性 | 有惰性,不設置就不會立即執行 | 沒有惰性,會立即執行 |
參數 | 語法上多個參數 | 不需要傳遞參數 |
獲取值 | 可以獲取到新舊值 | 不能獲取到新舊值 |