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