VUE3中watch監(jiān)聽使用實例詳解
watch介紹
vue中watch用來監(jiān)聽數(shù)據(jù)的響應式變化.獲取數(shù)據(jù)變化前后的值
watch的完整入參
watch(監(jiān)聽的數(shù)據(jù),副作用函數(shù),配置對象) watch(data, (newData, oldData) => {}, {immediate: true, deep: true})
watch監(jiān)聽的不同情況
創(chuàng)建響應式數(shù)據(jù)
import { ref, watch, reactive } from "vue"; let name = ref("moxun"); let age = ref(18); let person = reactive({ Hobby: "photo", city: { jiangsu: { nanjing: "雨花臺", }, }, });
1 監(jiān)聽單個refimpl數(shù)據(jù)
watch(name, (newName, oldName) => { console.log("newName", newName); });
2 監(jiān)聽多個refimpl數(shù)據(jù)
方式一:vue3允許多個watch監(jiān)聽器存在
watch(name, (newValue, oldValue) => { console.log("new", newValue, "old", oldValue); }); watch(age, (newValue, oldValue) => { console.log("new", newValue, "old", oldValue); });
方式二:將需要監(jiān)聽的數(shù)據(jù)添加到數(shù)組
watch([name, age], (newValue, oldValue) => { // 返回的數(shù)據(jù)是數(shù)組 console.log("new", newValue, "old", oldValue); });
3 監(jiān)聽proxy數(shù)據(jù)
注意
1.此時vue3將強制開啟deep深度監(jiān)聽
2.當監(jiān)聽值為proxy對象時,oldValue值將出現(xiàn)異常,此時與newValue相同
// 監(jiān)聽proxy對象 watch(person, (newValue, oldValue) => { console.log("newValue", newValue, "oldValue", oldValue); });
4 監(jiān)聽proxy數(shù)據(jù)的某個屬性
需要將監(jiān)聽值寫成函數(shù)返回形式,vue3無法直接監(jiān)聽對象的某個屬性變化
watch( () => person.Hobby, (newValue, oldValue) => { console.log("newValue",newValue, "oldvalue", oldValue); } );
注意
當監(jiān)聽proxy對象的屬性為復雜數(shù)據(jù)類型時,需要開啟deep深度監(jiān)聽
watch( () => person.city, (newvalue, oldvalue) => { console.log("person.city newvalue", newvalue, "oldvalue", oldvalue); },{ deep: true } );
5 監(jiān)聽proxy數(shù)據(jù)的某些屬性
watch([() => person.age, () => person.name], (newValue, oldValue) => { // 此時newValue為數(shù)組 console.log("person.age", newValue, oldValue); });
總結
1.與vue2中的watch配置一致
2.兩個坑:
監(jiān)聽reactive定義的proxy代理數(shù)據(jù)時
oldValue無法正確獲取
強制開啟deep深度監(jiān)聽(無法關閉)
監(jiān)聽reactive定義的proxy代理對象某個屬性時deep配置項生效
到此這篇關于VUE3中watch監(jiān)聽使用的文章就介紹到這了,更多相關VUE3 watch監(jiān)聽使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue+element?ui表格添加多個搜索條件篩選功能(前端查詢)
這篇文章主要給大家介紹了關于vue+element?ui表格添加多個搜索條件篩選功能的相關資料,最近在使用element-ui的表格組件時,遇到了搜索框功能的實現(xiàn)問題,需要的朋友可以參考下2023-08-08vue性能優(yōu)化之cdn引入vue-Router的問題
這篇文章主要介紹了vue性能優(yōu)化之cdn引入vue-Router的問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08vue解析Json數(shù)據(jù)獲取Json里面的多個id問題
這篇文章主要介紹了vue解析Json數(shù)據(jù)獲取Json里面的多個id問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12Vuex處理用戶Token過期及優(yōu)化設置封裝本地存儲操作模塊
這篇文章主要為大家介紹了Vuex處理用戶Token優(yōu)化設置封裝本地存儲操作模塊及Token?過期問題詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09