airi 中的 VueUse `watchThrottled` 详解:带节流的响应式 watcher 与 leading/trailing 控制实战
airi 中的 VueUse watchThrottled 详解:带节流的响应式 watcher 与 leading/trailing 控制实战
本篇基于 airi 仓库内置的 VueUse 函数参考文档 watchThrottled,系统讲解 watchThrottled 这一“节流版 watch”的完整用法、throttle / trailing / leading 三个专属选项、throttleFilter + watchWithFilter 的底层机制与类型声明,并结合 airi 仓库中 refThrottled、useThrottleFn、watchDebounced 等兄弟 API 的真实调用点,给出可直接落地的响应式节流实践方案。
一、watchThrottled 的定位:给 watch 回调加上“限流弹簧”
watchThrottled 是 VueUse(@vueuse/core)提供的节流 watcher:与原生 watch 类似地监听响应式来源,但回调函数在指定时间间隔内最多被调用一次(原文档表述为 "The callback will be invoked at most once per specified duration")。
它在 airi 仓库中的来源是一份随仓库分发的 VueUse 决策与实现指南(skill):
- 入口索引 SKILL.md 将所有函数按 State / Elements / Watch / Reactivity 等分类,
watchThrottled位于 Watch 分类下,Invocation规则为AUTO——即在该 skill 的应用场景(Vue 3 / Nuxt 3 项目)中可自动优先选用; - 同步信息见 SYNC.md,该 skill 集源自
vendor/vueuse/skills/vueuse-functions的某个具体 Git SHA,同步于 2026-06-22,因此文档内容与具体 VueUse 版本对齐; - airi 工作区通过 pnpm catalog 统一锁定了 VueUse 版本,pnpm-workspace.yaml 中声明
'@vueuse/core': ^14.4.0,各应用(apps/stage-web、apps/stage-tamagotchi等)的 package.json 均以"@vueuse/core": "catalog:"引用同一版本。
从工程语义上看,watchThrottled 解决的是 Vue 响应式场景中的经典问题:源值变化频率远高于处理逻辑所需频率(鼠标坐标、窗口尺寸、滚动位置、高频状态更新),此时逐个触发回调会造成无谓的计算与渲染开销,需要在 watcher 层面做“限流”。
二、基本用法与完整选项
2.1 最简示例
与 watch 用法一致,但额外接受 throttle、trailing、leading 三个作用于回调函数的选项:
import { watchThrottled } from '@vueuse/core'
watchThrottled(
source,
() => { console.log('changed!') },
{ throttle: 500 },
)
2.2 选项表(完整继承自参考文档)
| Option | Type | Default | Description |
|---|---|---|---|
throttle |
MaybeRefOrGetter<number> |
0 |
节流间隔(毫秒),可以是响应式的 |
trailing |
boolean |
true |
是否在节流窗口的尾沿(trailing edge)调用回调 |
leading |
boolean |
true |
是否在节流窗口的首沿(leading edge)调用回调 |
除上述专属选项外,所有标准 watch 选项均受支持(deep、immediate、flush 等),这一点与 watchDebounced 的选项继承方式一致,可对照 watchDebounced 参考。
两个值得注意的实现细节:
throttle是可响应的。其类型为MaybeRefOrGetter<number>,意味着可以传入ref或 getter,在运行期动态调整节流间隔——这与watchDebounced的“Reactive Debounce Time”能力同构;- 返回值是
WatchHandle(见类型声明),组件卸载或作用域销毁时 watcher 会被自动清理,也支持手动调用停止,行为与普通watch的返回句柄一致。
三、leading 与 trailing:回调触发时机的精细控制
leading / trailing 决定节流窗口内回调在“哪一端”触发,参考文档给出的两种典型组合:
import { watchThrottled } from '@vueuse/core'
// Only invoke at the start of each throttle period
watchThrottled(source, callback, {
throttle: 500,
leading: true,
trailing: false,
})
// Only invoke at the end of each throttle period
watchThrottled(source, callback, {
throttle: 500,
leading: false,
trailing: true,
})
leading: true, trailing: false:窗口开启时立即执行一次,窗口内的后续变化被合并丢弃,直到下一个窗口。适合“首帧必须响应、后续允许丢帧”的场景(如拖拽过程中实时绘制);leading: false, trailing: true:只保留每个窗口末尾的最新一次触发,确保最终值一定被处理,适合“只要终态、不要中间态”的场景(如表单防抖式提交、尺寸同步);- 两者同时为
true(默认):窗口首尾各执行一次,窗口内变化被合并,兼顾即时响应与终态保证。
这套首尾语义与函数级节流 useThrottleFn(fn, ms, trailing?, leading?, rejectOnCancel?) 完全一致,见 useThrottleFn 参考。二者的差别仅在于作用面:useThrottleFn 限流任意函数,watchThrottled 则把限流直接内建进 watch 的触发链路。
四、工作原理:watchWithFilter + throttleFilter 的语法糖
参考文档明确给出其本质——watchThrottled 是下面代码的简写:
import { throttleFilter, watchWithFilter } from '@vueuse/core'
watchWithFilter(
source,
() => { console.log('changed!') },
{
eventFilter: throttleFilter(500),
},
)
这揭示了 VueUse Watch 分类的统一设计:watchWithFilter 提供 eventFilter 选项位,任何符合 ConfigurableEventFilter 的过滤器(throttleFilter、debounceFilter、pausableFilter 或自定义过滤器)都可以挂载进去。因此:
watchThrottled≈watchWithFilter+throttleFilter(对应watchDebounced≈watchWithFilter+debounceFilter);- 需要文档未覆盖的自定义限流策略(如“按帧合并”“超过 N 次强制触发”)时,可以直接使用
watchWithFilter传入自定义eventFilter,而不是放弃watch手写定时器; throttle选项的响应式能力(MaybeRefOrGetter)也正是通过ConfigurableEventFilter的动态重配置能力实现的——从源码结构看,过滤器在每次触发时读取当前间隔值,而非创建时固化。
五、类型声明与重载
参考文档完整给出的类型声明如下:
export interface WatchThrottledOptions<
Immediate,
> extends WatchOptions<Immediate> {
throttle?: MaybeRefOrGetter<number>
trailing?: boolean
leading?: boolean
}
export declare function watchThrottled<
T,
Immediate extends Readonly<boolean> = false,
>(
source: WatchSource<T>,
cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
options?: WatchThrottledOptions<Immediate>,
): WatchHandle
export declare function watchThrottled<
T extends Readonly<MultiWatchSources>,
Immediate extends Readonly<boolean> = false,
>(
sources: [...T],
cb: WatchCallback<MapSources<T>, MapOldSources<T, Immediate>>,
options?: WatchThrottledOptions<Immediate>,
): WatchHandle
export declare function watchThrottled<
T extends object,
Immediate extends Readonly<boolean> = false,
>(
source: T,
cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
options?: WatchThrottledOptions<Immediate>,
): WatchHandle
/** @deprecated use `watchThrottled` instead */
export declare const throttledWatch: typeof watchThrottled
要点解读:
- 三个重载分别对应 Vue 的三种
watch来源形态:单个WatchSource<T>、来源数组[...T](回调收到MapSources映射后的数组,且Immediate extends true ? T | undefined : T的取值语义与原生watch一致)、以及深层响应式对象T extends object(此时回调的newVal参数就是对象本身); WatchThrottledOptions继承WatchOptions,在类型层面保证标准选项(immediate、deep、flush等)与专属选项共存,immediate与throttle的组合也是合法的;- 旧名
throttledWatch已标记@deprecated,frontmatter 中alias: throttledWatch也印证了这一点——迁移旧代码时统一替换为watchThrottled即可,二者类型上完全等价(typeof watchThrottled)。
六、兄弟 API 对照:refThrottled、useThrottleFn、watchDebounced
同属 skill 参考集的几个相关原语,选择时可按下表对照(各参考文档路径见文末索引):
| API | 作用面 | 关键参数 | 典型场景 |
|---|---|---|---|
watchThrottled |
watcher 回调 | throttle(可响应式)、leading、trailing + 全部 watch 选项 |
高频响应式来源需要限流触发回调 |
| refThrottled | ref 的值 | delay、trailing(第 3 参)、leading(第 4 参) |
让下游直接消费一个“节流后的新 ref” |
| useThrottleFn | 任意函数 | ms(可响应式)、trailing、leading、rejectOnCancel |
限流事件处理器(resize/scroll 等),不绑定 watch |
| watchDebounced | watcher 回调 | debounce(可响应式)、maxWait + 全部 watch 选项 |
只在来源停止变化后触发(等待终态) |
选择口诀:要“消费节流后的值”用 refThrottled;要“限流函数本身”用 useThrottleFn;要“稳定间隔内的最新触发”用 watchThrottled;要“停顿后的终态”用 watchDebounced。
七、airi 仓库中的节流/防抖真实调用点
从源码搜索看,airi 当前仓库直接调用的主要是同族中的 refThrottled、useThrottleFn 与 watchDebounced(watchThrottled 本身暂无直接调用点),这些用例恰好展示了该套过滤器体系在 stage 应用中的落法:
7.1 手势识别中的 refThrottled 采样(gesture-circle)
apps/stage-web/src/pages/devtools/gesture-circle.vue(桌面端 stage-pocket 版本 同构)用 usePointer 获取高频鼠标坐标后,同时派生两个 ref:
const pointThrottled = refThrottled(pointComputed, 50)
const pointDebounced = refDebounced(pointComputed, 50)
其中 pointThrottled 以 50ms 间隔稳定采样坐标点并推入 lastPoints 数组(第 125-127 行),用于圆度统计;pointDebounced 则在手停后触发一次性圆判定(标准差 < 20 判定为圆)。这正体现了“节流保连续采样 + 防抖取终态判定”的组合模式——如果换成 watchThrottled(pointComputed, cb, { throttle: 50 }),则可以把采样逻辑直接写在回调里而不需要中间 ref,两种写法在语义上等价。
7.2 时序图表宽更新中的 useThrottleFn
packages/stage-ui/src/components/gadgets/time-series-chart.vue 在监听容器宽度变化时,把宽度写入本地 ref 的动作包在 100ms 节流中:
const throttledWidth = ref(0)
const updateWidth = useThrottleFn(() => {
throttledWidth.value = Math.max(0, Math.floor(timeSeriesChartContainerBounding.width.value || 0))
}, 100, true, true)
watch(() => timeSeriesChartContainerBounding.width.value, updateWidth, { immediate: true })
注意这里显式传了 trailing: true, leading: true,即首尾都执行——窗口首帧立即获得宽度、窗口结束时再取最终宽度,保证图表在拖动窗口过程中既不卡顿又不丢失终态。此处若改用 watchThrottled,可等价写成 watchThrottled(() => ...width.value, updateWidth, { throttle: 100, immediate: true })(leading/trailing 默认即为 true)。
7.3 对照面:watchDebounced 的“等待终态”用法
仓库中 watchDebounced 的分布则展示了与之互补的防抖面:
- packages/stage-ui/src/stores/modules/airi-card.ts:角色卡片同步请求使用
watchDebounced(cards, requestCardSynchronization, { debounce: 1500, deep: true }),深度监听卡片列表,停止变更 1.5 秒后才发起同步请求,避免批量编辑过程中重复请求; - 语音提供商设置页(如 elevenlabs.vue、alibaba-cloud-model-studio.vue):对
apiKey/baseUrl两个 getter 组合源做 500ms 防抖,输入停顿后才加载音色列表; - apps/stage-tamagotchi/src/renderer/composables/use-screen-ambient-light.ts:屏幕环境光采集在窗口/显示器“安定”后(
debounce: displaySettleMs)才重启抓取,注释明确说明了动机——窗口移动或显示器重缩放期间不应反复重启采集流。
可以推断:在“窗口移动/重缩放导致来源短暂高频抖动、只需处理安定后状态”的这类需求上,watchDebounced 是终态选择;若同一场景还需要处理过程中的稳定频率反馈(如环境光实时预览),则 watchThrottled 是更合适的补位工具,而二者都通过 watchWithFilter 的 eventFilter 机制可自定义组合。
八、适用前提与实践注意事项
- 版本前提:
watchThrottled属于@vueuse/core,airi 工作区统一使用^14.4.0(pnpm-workspace.yaml);参考文档由 vendored skill 同步而来(SYNC.md),跨大版本引入 VueUse 时建议以对应版本的类型声明为准。 throttle: 0的默认值:参考文档表中throttle默认0,即不显式给出节流间隔时退化为普通watch的触发行为——使用时应始终显式声明间隔,避免误以为“默认就有节流”。immediate: true与首沿:immediate触发发生在 watch 创建时,leading: false时首次触发是否会排队进节流窗口属于边界行为,实际效果应以所用 VueUse 版本的测试/实现为准,仓库内文档未单独说明该组合。- 响应式间隔:
throttle接受MaybeRefOrGetter<number>,适合“根据设备性能动态调整刷新率”一类的自适应节流(如 SKILL.md 所倡导的“用 composable 而非自写代码”的风格)。 - 清理:返回
WatchHandle,组件内调用时无需手动stop(随作用域销毁自动停止);在 setup 之外的长生命周期调用中可显式保留 handle 用于提前终止。
九、参考文件索引
| 文件 | 说明 |
|---|---|
| .agents/skills/vueuse-functions/references/watchThrottled.md | 本文主体参考文档:用法、选项表、leading/trailing、原理、类型声明 |
| .agents/skills/vueuse-functions/SKILL.md | Watch 分类索引,watchThrottled 的 Invocation: AUTO 规则 |
| .agents/skills/vueuse-functions/SYNC.md | 参考文档集的来源 SHA 与同步时间 |
| .agents/skills/vueuse-functions/references/watchWithFilter.md | eventFilter 机制(watchThrottled 的底座) |
| .agents/skills/vueuse-functions/references/useThrottleFn.md | 函数级节流,trailing/leading 语义对照 |
| .agents/skills/vueuse-functions/references/refThrottled.md | ref 值级节流(含对象 ref 行为示例) |
| .agents/skills/vueuse-functions/references/watchDebounced.md | 防抖 watcher 对照 |
| pnpm-workspace.yaml | @vueuse/core 版本 catalog(^14.4.0) |
| apps/stage-web/src/pages/devtools/gesture-circle.vue | refThrottled / refDebounced 手势采样实战 |
| packages/stage-ui/src/components/gadgets/time-series-chart.vue | useThrottleFn 容器宽度限流更新 |
| packages/stage-ui/src/stores/modules/airi-card.ts | watchDebounced 深度监听 + 1500ms 防抖同步 |
| apps/stage-tamagotchi/src/renderer/composables/use-screen-ambient-light.ts | 显示器安定后重启采集的防抖实例 |