Vue3中watch監(jiān)聽對象的屬性值(監(jiān)聽源必須是一個getter函數(shù))
Vue3 中使用 watch 偵聽對象中的具體屬性
1.前言
<script lang="ts" setup>
// 接受父組件傳遞的數(shù)據(jù)
const props = defineProps({
test: {
type: String,
default: ''
}
})
// 使用 watch 偵聽 props 中的 test 屬性
watch(
// 這種寫法不會偵聽到 props 中 test 的變化
props.test,
() => {
console.log("偵聽成功")
}
)
watch(
// 這種寫法會偵聽到 props 中 test 的變化
() => props.test,
() => {
console.log("偵聽成功")
}
)
</script>watch 的基本用法
watch() 默認是懶偵聽的,即僅在偵聽源發(fā)生變化時才執(zhí)行回調(diào)函數(shù)
第一個參數(shù):偵聽源,偵聽源可以是一下幾種
一個函數(shù),返回一個值一個 ref一個響應式對象(reactive)或是由以上類型的值組成的數(shù)組第二個參數(shù):偵聽源發(fā)生變化時要觸發(fā)的回調(diào)函數(shù)。
? (newValue, oldValue) => { /* code */}
? 當偵聽多個來源時,回調(diào)函數(shù)接受兩個數(shù)組,分別對應源數(shù)組中的新值和舊值
? ( [ newValue1, newValue2 ] , [ oldValue1 , oldValue2 ]) => {/* code */}
第三個參數(shù):可選對象,可以支持一下這些選項
immediate:偵聽器創(chuàng)建時立即觸發(fā)回調(diào)deep:如果源是一個對象,會強制深度遍歷,以便在深層級發(fā)生變化時觸發(fā)回調(diào)函數(shù)flush:調(diào)整回調(diào)函數(shù)的刷新時機onTrack / onTrigger:調(diào)試偵聽器的依賴
2. 原因
因為watch的偵聽源只能是上面的4中情況
const obj = reactive({ count: 0 })
// 錯誤,因為 watch() 中的偵聽源是一個 number,最終 source 返回的 getter 函數(shù)是一個空,所以就得不到偵聽的數(shù)據(jù)
watch(obj.count, (count) => {
console.log(`count is: ${count}`)
})
// 正確,主要思想是,將偵聽源轉(zhuǎn)化為以上4種類型(轉(zhuǎn)化為getter函數(shù)是最簡單方便的)
watch(
() => obj.count,
(count) => {
console.log(`count is: ${count}`)
}
)3.watch源碼分析
export function watch<T = any, Immediate extends Readonly<boolean> = false>(
source: T | WatchSource<T>,
cb: any,
options?: WatchOptions<Immediate>
): WatchStopHandle {
if (__DEV__ && !isFunction(cb)) {
warn(
`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
`Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
`supports \`watch(source, cb, options?) signature.`
)
}
return doWatch(source as any, cb, options)
}從源碼中可以看出,watch接收三個參數(shù):source偵聽源、cb回調(diào)函數(shù)、options偵聽配置,最后會返回一個doWatch
4.doWatch源碼分析
function doWatch(
source: WatchSource | WatchSource[] | WatchEffect | object,
cb: WatchCallback | null,
{ immediate, deep, flush, onTrack, onTrigger }: WatchOptions = EMPTY_OBJ
): WatchStopHandle {
// ...
// 當前組件實例
const instance = currentInstance
// 副作用函數(shù),在初始化effect時使用
let getter: () => any
// 強制觸發(fā)偵聽
let forceTrigger = false
// 是否為多數(shù)據(jù)源。
let isMultiSource = false
}doWatch依然接受三個參數(shù):source偵聽源、cb回調(diào)函數(shù)、options偵聽配置
這里著重對偵聽源的源碼進行分析(source標準化)
- 如果
source是ref類型,getter是個返回source.value的函數(shù),forceTrigger取決于source是否是淺層響應式。
if (isRef(source)) {
getter = () => source.value
forceTrigger = isShallow(source)
}- 如果
source是reactive類型,getter是個返回source的函數(shù),并將deep設置為true。 當直接偵聽一個響應式對象時,偵聽器會自動啟用深層模式
if (isReactive(source)) {
getter = () => source
deep = true
}例子
<template>
<div class="container">
<h2>obj---{{ obj }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年齡</button>
</div>
</template>
<script lang="ts" setup>
import { reactive, watch } from "vue";
const obj = reactive({
name: "張三",
age: 18,
});
const changeName = () => {
obj.name += "++";
};
const changeAge = () => {
obj.age += 1;
};
// obj 中的任一屬性變化了,都會被監(jiān)聽到
watch(obj, () => {
console.log("變化了");
});
</script>- 如果
source是個數(shù)組,將isMultiSource設為true,forceTrigger取決于source是否有reactive類型的數(shù)據(jù),getter函數(shù)中會遍歷source,針對不同類型的source做不同處理。
if (isArray(source)) {
isMultiSource = true
forceTrigger = source.some(isReactive)
getter = () =>
source.map(s => {
if (isRef(s)) {
return s.value
} else if (isReactive(s)) {
return traverse(s)
} else if (isFunction(s)) {
return callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER)
} else {
__DEV__ && warnInvalidSource(s)
}
})
}- 如果
source是個function。存在cb的情況下,getter函數(shù)中會執(zhí)行source,這里source會通過callWithErrorHandling函數(shù)執(zhí)行,在callWithErrorHandling中會處理source執(zhí)行過程中出現(xiàn)的錯誤;不存在cb的話,在getter中,如果組件已經(jīng)被卸載了,直接return,否則判斷cleanup(cleanup是在watchEffect中通過onCleanup注冊的清理函數(shù)),如果存在cleanup執(zhí)行cleanup,接著執(zhí)行source,并返回執(zhí)行結果。source會被callWithAsyncErrorHandling包裝,該函數(shù)作用會處理source執(zhí)行過程中出現(xiàn)的錯誤,與callWithErrorHandling不同的是,callWithAsyncErrorHandling會處理異步錯誤。
if (isFunction(source)) {
if (cb) {
getter = () =>
callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER)
} else {
// watchEffect
getter = () => {
// 如果組件實例已經(jīng)卸載,直接return
if (instance && instance.isUnmounted) {
return
}
// 如果清理函數(shù),則執(zhí)行清理函數(shù)
if (cleanup) {
cleanup()
}
// 執(zhí)行source,傳入onCleanup,用來注冊清理函數(shù)
return callWithAsyncErrorHandling(
source,
instance,
ErrorCodes.WATCH_CALLBACK,
[onCleanup]
)
}
}
}- 其他情況
getter會被賦值為一個空函數(shù)
getter = NOOP __DEV__ && warnInvalidSource(source)
5.總結
其實,source標準化主要是根據(jù)source的類型,將其變成 getter 函數(shù)
- 如果
source是ref對象,則創(chuàng)建一個訪問source.value的getter函數(shù) - 如果
source是一個reactive對象,則創(chuàng)建一個訪問source的getter函數(shù),并將deep設置為true如果source是一個函數(shù),則會進一步進行判斷第二個參數(shù)cb是否存在。 - 最后的
getter就是一個簡單的對source封裝的函數(shù)如果source是一個數(shù)組,則會對數(shù)組中的每個元素進行判斷并且返回相應的getter函數(shù)。 - 最后返回一個各種
getter函數(shù)封裝成的一個數(shù)組
整個doWatch 方法中的邏輯主要分為一下幾步:
- 通過getter函數(shù)來獲取數(shù)據(jù)源的值
- 通過job方法來調(diào)用傳入watch中的cb
- job中通過調(diào)用runner,runner調(diào)用getter獲取數(shù)據(jù)源新值
- doWatch中閉包緩存了數(shù)據(jù)源的舊值
- 將新舊值作為參數(shù)調(diào)用cb
- 將job作為activeEffect的scheduler方法,在后續(xù)的數(shù)據(jù)修改導致的trigger中調(diào)用
- 首次調(diào)用,傳入了immediate調(diào)用job,未傳入調(diào)用runner,以數(shù)據(jù)源為被觀察者收集依賴實現(xiàn)響應式
偵聽的第一步就是需要通過正確的getter函數(shù)去獲取偵聽源的值,所以在使用watch偵聽數(shù)據(jù)時,務必保證偵聽源的類型是符合官方規(guī)定的類型的
到此這篇關于Vue3中watch監(jiān)聽對象的屬性值,監(jiān)聽源必須是一個getter函數(shù)的文章就介紹到這了,更多相關Vue3 watch監(jiān)聽對象內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue實現(xiàn)左右伸縮方式(el-drawer自定義位置展開收縮)
這篇文章主要介紹了vue實現(xiàn)左右伸縮方式(el-drawer自定義位置展開收縮),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
Vue報錯Component?name"Home"should?always?be?mult
這篇文章主要介紹了Vue報錯Component?name"Home"should?always?be?multi問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
一文詳解VueUse中useAsyncState的實現(xiàn)原理
在Vue 3 Composition API中,我們可以使用自定義鉤子函數(shù)來封裝可復用的邏輯,useAsyncState是一個用于管理異步狀態(tài)的自定義鉤子函數(shù),本文將給大家介紹一下useAsyncState的實現(xiàn)原理,感興趣的朋友可以參考下2024-01-01

