vue3 中使用 watch 侦听对象中的具体属性1.前言<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:调试侦听器的依赖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<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
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}
例子
<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监听对象的属性值的详细内容。