VUE3中watch監(jiān)聽使用實(shí)例詳解
watch介紹
vue中watch用來監(jiān)聽數(shù)據(jù)的響應(yīng)式變化.獲取數(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)建響應(yī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將強(qiáng)制開啟deep深度監(jiān)聽
2.當(dāng)監(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);
}
);
注意
當(dāng)監(jiān)聽proxy對象的屬性為復(fù)雜數(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);
});
總結(jié)
1.與vue2中的watch配置一致
2.兩個坑:
監(jiān)聽reactive定義的proxy代理數(shù)據(jù)時
oldValue無法正確獲取
強(qiáng)制開啟deep深度監(jiān)聽(無法關(guān)閉)
監(jiān)聽reactive定義的proxy代理對象某個屬性時deep配置項(xiàng)生效
到此這篇關(guān)于VUE3中watch監(jiān)聽使用的文章就介紹到這了,更多相關(guān)VUE3 watch監(jiān)聽使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue項(xiàng)目動態(tài)設(shè)置頁面title及是否緩存頁面的問題
這篇文章主要介紹了vue項(xiàng)目動態(tài)設(shè)置頁面title及是否緩存頁面的問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
vue.js中window.onresize的超詳細(xì)使用方法
這篇文章主要給大家介紹了關(guān)于vue.js中window.onresize的超詳細(xì)使用方法,window.onresize 是直接給window的onresize屬性綁定事件,只能有一個,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
vue項(xiàng)目中引入vue-datepicker插件的詳解
這篇文章主要介紹了vue項(xiàng)目中引入vue-datepicker插件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05
vue-element-admin登錄攔截設(shè)置白名單方式
這篇文章主要介紹了vue-element-admin登錄攔截設(shè)置白名單方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03

