VUE3中watch監(jiān)聽使用實例詳解
watch介紹
vue中watch用來監(jiān)聽數(shù)據(jù)的響應式變化.獲取數(shù)據(jù)變化前后的值
watch的完整入?yún)?/p>
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項目動態(tài)設置頁面title及是否緩存頁面的問題
這篇文章主要介紹了vue項目動態(tài)設置頁面title及是否緩存頁面的問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
vue.js中window.onresize的超詳細使用方法
這篇文章主要給大家介紹了關于vue.js中window.onresize的超詳細使用方法,window.onresize 是直接給window的onresize屬性綁定事件,只能有一個,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-12-12

