<script lang="ts" setup> // 接受父组件传递的数据 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() 默认是懒侦听的,即仅在侦听源发生变化时才执行回调函数第一个参数:侦听源,侦听源可以是一下几种一个函数,返回一个值一个 ref一个响应式对象(reactive)或是由以上类型的值组成的数组第二个参数:侦听源发生变化时要触发的回调函数。(newValue, oldValue) => { /* code */}当侦听多个来源时,回调函数接受两个数组,分别对应源数组中的新值和旧值( [ newValue1, newValue2 ] , [ oldValue1 , oldValue2 ]) => {/* code */}第三个参数:可选对象,可以支持一下这些选项immediate:侦听器创建时立即触发回调deep:如果源是一个对象,会强制深度遍历,以便在深层级发生变化时触发回调函数flush:调整回调函数的刷新时机onTrack / onTrigger:调试侦听器的依赖
因为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}`) } )
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接收三个参数:source侦听源、cb回调函数、options侦听配置,最后会返回一个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 }
例子
<template> <div class="container"> <h3>obj---{{ obj }}</h3> <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 中的任一属性变化了,都会被监听到 watch(obj, () => { console.log("变化了"); }); </script>
如果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)
以上就是Vue3中怎么使用watch监听对象的属性值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号