Vue3中watch監(jiān)聽對(duì)象的屬性值(監(jiān)聽源必須是一個(gè)getter函數(shù))
Vue3 中使用 watch 偵聽對(duì)象中的具體屬性
1.前言
<script lang="ts" setup>
// 接受父組件傳遞的數(shù)據(jù)
const props = defineProps({
test: {
type: String,
default: ''
}
})
// 使用 watch 偵聽 props 中的 test 屬性
watch(
// 這種寫法不會(huì)偵聽到 props 中 test 的變化
props.test,
() => {
console.log("偵聽成功")
}
)
watch(
// 這種寫法會(huì)偵聽到 props 中 test 的變化
() => props.test,
() => {
console.log("偵聽成功")
}
)
</script>watch 的基本用法
watch() 默認(rèn)是懶偵聽的,即僅在偵聽源發(fā)生變化時(shí)才執(zhí)行回調(diào)函數(shù)
第一個(gè)參數(shù):偵聽源,偵聽源可以是一下幾種
一個(gè)函數(shù),返回一個(gè)值一個(gè) ref一個(gè)響應(yīng)式對(duì)象(reactive)或是由以上類型的值組成的數(shù)組第二個(gè)參數(shù):偵聽源發(fā)生變化時(shí)要觸發(fā)的回調(diào)函數(shù)。
? (newValue, oldValue) => { /* code */}
? 當(dāng)偵聽多個(gè)來源時(shí),回調(diào)函數(shù)接受兩個(gè)數(shù)組,分別對(duì)應(yīng)源數(shù)組中的新值和舊值
? ( [ newValue1, newValue2 ] , [ oldValue1 , oldValue2 ]) => {/* code */}
第三個(gè)參數(shù):可選對(duì)象,可以支持一下這些選項(xiàng)
immediate:偵聽器創(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)試偵聽器的依賴
2. 原因
因?yàn)?code>watch的偵聽源只能是上面的4中情況
const obj = reactive({ count: 0 })
// 錯(cuò)誤,因?yàn)?watch() 中的偵聽源是一個(gè) number,最終 source 返回的 getter 函數(shù)是一個(gè)空,所以就得不到偵聽的數(shù)據(jù)
watch(obj.count, (count) => {
console.log(`count is: ${count}`)
})
// 正確,主要思想是,將偵聽源轉(zhuǎn)化為以上4種類型(轉(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偵聽源、cb回調(diào)函數(shù)、options偵聽配置,最后會(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ā)偵聽
let forceTrigger = false
// 是否為多數(shù)據(jù)源。
let isMultiSource = false
}doWatch依然接受三個(gè)參數(shù):source偵聽源、cb回調(diào)函數(shù)、options偵聽配置
這里著重對(duì)偵聽源的源碼進(jìn)行分析(source標(biāo)準(zhǔn)化)
- 如果
source是ref類型,getter是個(gè)返回source.value的函數(shù),forceTrigger取決于source是否是淺層響應(yīng)式。
if (isRef(source)) {
getter = () => source.value
forceTrigger = isShallow(source)
}- 如果
source是reactive類型,getter是個(gè)返回source的函數(shù),并將deep設(shè)置為true。 當(dāng)直接偵聽一個(gè)響應(yīng)式對(duì)象時(shí),偵聽器會(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)聽到
watch(obj, () => {
console.log("變化了");
});
</script>- 如果
source是個(gè)數(shù)組,將isMultiSource設(shè)為true,forceTrigger取決于source是否有reactive類型的數(shù)據(jù),getter函數(shù)中會(huì)遍歷source,針對(duì)不同類型的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ì)通過callWithErrorHandling函數(shù)執(zhí)行,在callWithErrorHandling中會(huì)處理source執(zhí)行過程中出現(xiàn)的錯(cuò)誤;不存在cb的話,在getter中,如果組件已經(jīng)被卸載了,直接return,否則判斷cleanup(cleanup是在watchEffect中通過onCleanup注冊(cè)的清理函數(shù)),如果存在cleanup執(zhí)行cleanup,接著執(zhí)行source,并返回執(zhí)行結(jié)果。source會(huì)被callWithAsyncErrorHandling包裝,該函數(shù)作用會(huì)處理source執(zhí)行過程中出現(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,用來注冊(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的類型,將其變成 getter 函數(shù)
- 如果
source是ref對(duì)象,則創(chuàng)建一個(gè)訪問source.value的getter函數(shù) - 如果
source是一個(gè)reactive對(duì)象,則創(chuàng)建一個(gè)訪問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 方法中的邏輯主要分為一下幾步:
- 通過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ù)修改導(dǎo)致的trigger中調(diào)用
- 首次調(diào)用,傳入了immediate調(diào)用job,未傳入調(diào)用runner,以數(shù)據(jù)源為被觀察者收集依賴實(shí)現(xiàn)響應(yīng)式
偵聽的第一步就是需要通過正確的getter函數(shù)去獲取偵聽源的值,所以在使用watch偵聽數(shù)據(jù)時(shí),務(wù)必保證偵聽源的類型是符合官方規(guī)定的類型的
到此這篇關(guān)于Vue3中watch監(jiān)聽對(duì)象的屬性值,監(jiān)聽源必須是一個(gè)getter函數(shù)的文章就介紹到這了,更多相關(guān)Vue3 watch監(jiān)聽對(duì)象內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何搭建一個(gè)完整的Vue3.0+ts的項(xiàng)目步驟
這篇文章主要介紹了如何搭建一個(gè)完整的Vue3.0+ts的項(xiàng)目步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
Vue的v-model的幾種修飾符.lazy,.number和.trim的用法說明
這篇文章主要介紹了Vue的v-model的幾種修飾符.lazy,.number和.trim的用法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-08-08
vue-resource:jsonp請(qǐng)求百度搜索的接口示例
今天小編就為大家分享一篇vue-resource:jsonp請(qǐng)求百度搜索的接口示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Vue導(dǎo)入Echarts實(shí)現(xiàn)散點(diǎn)圖
這篇文章主要為大家詳細(xì)介紹了Vue導(dǎo)入Echarts實(shí)現(xiàn)散點(diǎn)圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-12-12
vue?cli3?項(xiàng)目中如何使用axios發(fā)送post請(qǐng)求
這篇文章主要介紹了vue?cli3?項(xiàng)目中如何使用axios發(fā)送post請(qǐng)求,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
優(yōu)雅的處理vue項(xiàng)目異常實(shí)戰(zhàn)記錄
這篇文章主要給大家介紹了關(guān)于如何優(yōu)雅的處理vue項(xiàng)目異常的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用vue具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
Vue.js實(shí)現(xiàn)雙向數(shù)據(jù)綁定方法(表單自動(dòng)賦值、表單自動(dòng)取值)
今天小編就為大家分享一篇Vue.js實(shí)現(xiàn)雙向數(shù)據(jù)綁定方法(表單自動(dòng)賦值、表單自動(dòng)取值),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08

