Vue3 中使用 watch 侦听对象中的具体属性
1.前言
watch 的基本用法
watch() 默认是懒侦听的,即仅在侦听源发生变化时才执行回调函数第一个参数:侦听源,侦听源可以是一下几种一个函数,返回一个值一个 ref一个响应式对象(reactive)或是由以上类型的值组成的数组第二个参数:侦听源发生变化时要触发的回调函数。(newValue, oldValue) => { /* code */}当侦听多个来源时,回调函数接受两个数组,分别对应源数组中的新值和旧值( [ newValue1, newValue2 ] , [ oldValue1 , oldValue2 ]) => {/* code */}第三个参数:可选对象,可以支持一下这些选项immediate:侦听器创建时立即触发回调deep:如果源是一个对象,会强制深度遍历,以便在深层级发生变化时触发回调函数flush:调整回调函数的刷新时机onTrack / onTrigger:调试侦听器的依赖
2. 原因
因为watch的侦听源只能是上面的4中情况
const obj = reactive({ count: 0 })
// 错误,因为 watch() 中的侦听源是一个 number,最终 source 返回的 getter 函数是一个空,所以就得不到侦听的数据
watch(obj.count, (count) => {
console.log(`count is: ${count}`)
})
// 正确,主要思想是,将侦听源转化为以上4种类型(转化为getter函数是最简单方便的)
watch(
() => obj.count,
(count) => {
console.log(`count is: ${count}`)
}
)3.watch源码分析
export function watch= false>( source: T | WatchSource , cb: any, options?: WatchOptions ): 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接收三个参数:source侦听源、cb回调函数、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
// 副作用函数,在初始化effect时使用
let getter: () => any
// 强制触发侦听
let forceTrigger = false
// 是否为多数据源。
let isMultiSource = false
}doWatch依然接受三个参数:source侦听源、cb回调函数、options侦听配置
这里着重对侦听源的源码进行分析(source标准化)
立即学习“前端免费学习笔记(深入)”;
如果
source是ref类型,getter是个返回source.value的函数,forceTrigger取决于source是否是浅层响应式。
if (isRef(source)) {
getter = () => source.value
forceTrigger = isShallow(source)
}如果
source是reactive类型,getter是个返回source的函数,并将deep设置为true。 当直接侦听一个响应式对象时,侦听器会自动启用深层模式
if (isReactive(source)) {
getter = () => source
deep = true
}例子
obj---{{ obj }}
如果
source是个数组,将isMultiSource设为true,forceTrigger取决于source是否有reactive类型的数据,getter函数中会遍历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函数中会执行source,这里source会通过callWithErrorHandling函数执行,在callWithErrorHandling中会处理source执行过程中出现的错误;不存在cb的话,在getter中,如果组件已经被卸载了,直接return,否则判断cleanup(cleanup是在watchEffect中通过onCleanup注册的清理函数),如果存在cleanup执行cleanup,接着执行source,并返回执行结果。source会被callWithAsyncErrorHandling包装,该函数作用会处理source执行过程中出现的错误,与callWithErrorHandling不同的是,callWithAsyncErrorHandling会处理异步错误。
if (isFunction(source)) {
if (cb) {
getter = () =>
callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER)
} else {
// watchEffect
getter = () => {
// 如果组件实例已经卸载,直接return
if (instance && instance.isUnmounted) {
return
}
// 如果清理函数,则执行清理函数
if (cleanup) {
cleanup()
}
// 执行source,传入onCleanup,用来注册清理函数
return callWithAsyncErrorHandling(
source,
instance,
ErrorCodes.WATCH_CALLBACK,
[onCleanup]
)
}
}
}其他情况
getter会被赋值为一个空函数
getter = NOOP __DEV__ && warnInvalidSource(source)










