Skip to content

watchThrottled

类别
导出体积
530 B
上次更改
7 minutes ago
别名
throttledWatch

节流式监视。回调函数最多在指定的时间间隔内调用一次。

示例

延迟设置为1000毫秒以进行演示。

输入内容:

更新次数: 0

用法

类似于 watch,但提供了额外的选项 throttletrailingleading,这些选项将应用于回调函数。

ts
import { 
watchThrottled
} from '@vueuse/core'
watchThrottled
(
source, () => {
console
.
log
('changed!') },
{
throttle
: 500 },
)

选项

选项类型默认值说明
throttleMaybeRefOrGetter<number>0节流间隔时间(毫秒,可响应式)
trailingbooleantrue是否在节流时间结束时调用回调
leadingbooleantrue是否在节流时间开始时调用回调

所有标准的 watch 选项(如 deepimmediateflush 等)也都支持。

领先与滞后

控制回调函数调用的时机:

ts
import { 
watchThrottled
} from '@vueuse/core'
// 只在每个节流周期开始时调用
watchThrottled
(source, callback, {
throttle
: 500,
leading
: true,
trailing
: false,
}) // 只在每个节流周期结束时调用
watchThrottled
(source, callback, {
throttle
: 500,
leading
: false,
trailing
: true,
})

工作原理

实质上,它相当于以下代码的简写:

ts
import { 
throttleFilter
,
watchWithFilter
} from '@vueuse/core'
watchWithFilter
(
source, () => {
console
.
log
('changed!') },
{
eventFilter
:
throttleFilter
(500),
}, )

类型声明

显示类型声明
ts
export interface 
WatchThrottledOptions
<
Immediate
,
> extends WatchOptions<
Immediate
> {
throttle
?:
MaybeRefOrGetter
<number>
trailing
?: boolean
leading
?: boolean
} 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
,
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 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

源码

源码演示文档

贡献者

一纸忘忧

更新日志

没有最近的更新日志