主题
watchThrottled
节流监视器。回调函数将在指定的时间间隔内最多被调用一次。
🌐 Throttled watch. The callback will be invoked at most once per specified duration.
示例
用法
🌐 Usage
类似于 watch,但提供额外选项 throttle、trailing 和 leading,这些选项将应用于回调函数。
🌐 Similar to watch, but offering extra options throttle, trailing, and leading which will be applied to the callback function.
ts
import { watchThrottled } from '@vueuse/core'
watchThrottled(
source,
() => { console.log('changed!') },
{ throttle: 500 },
)选项
🌐 Options
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
throttle | MaybeRefOrGetter<number> | 0 | 节流间隔(毫秒,可响应式) |
trailing | boolean | true | 在尾部触发 |
leading | boolean | true | 在前端触发 |
所有标准 watch 选项(deep、immediate、flush 等)也受支持。
🌐 All standard watch options (deep, immediate, flush, etc.) are also supported.
前导和尾随
🌐 Leading and Trailing
控制回调何时被调用:
🌐 Control when the callback is invoked:
ts
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,
})工作原理
🌐 How It Works
它本质上是以下代码的简写:
🌐 It's essentially a shorthand for the following code:
ts
import { throttleFilter, watchWithFilter } from '@vueuse/core'
watchWithFilter(
source,
() => { console.log('changed!') },
{
eventFilter: throttleFilter(500),
},
)