Skip to content

watchDebounced ​

类别
导出大小
589 B
最近修改
7 months ago
别名
debouncedWatch

防抖监听。回调函数只有在源停止变化达到指定时间后才会被调用。

🌐 Debounced watch. The callback will only be invoked after the source stops changing for the specified duration.

示例 ​

Delay is set to 1000ms and maxWait is set to 5000ms for this demo.

Input:

Times Updated: 0

用法 ​

🌐 Usage

类似于 watch,但提供额外选项 debounce 和 maxWait,这些选项将应用于回调函数。

🌐 Similar to watch, but offering extra options debounce and maxWait which will be applied to the callback function.

ts
import { 
watchDebounced
} from '@vueuse/core'
watchDebounced
(
source, () => {
console
.
log
('changed!') },
{
debounce
: 500,
maxWait
: 1000 },
)

选项 ​

🌐 Options

选项类型默认值描述
debounceMaybeRefOrGetter<number>0防抖延迟(毫秒,可响应)
maxWaitMaybeRefOrGetter<number>—强制调用前的最长等待时间

所有标准 watch 选项(deep、immediate、flush 等)也受支持。

🌐 All standard watch options (deep, immediate, flush, etc.) are also supported.

响应去抖时间 ​

🌐 Reactive Debounce Time

去抖动时间可以是响应式的:

🌐 The debounce time can be reactive:

ts
import { 
watchDebounced
} from '@vueuse/core'
const
debounceMs
=
ref
(500)
watchDebounced
(
source, () => {
console
.
log
('changed!') },
{
debounce
:
debounceMs
},
) // Later, change the debounce time
debounceMs
.
value
= 1000

工作原理 ​

🌐 How It Works

它本质上是以下代码的简写:

🌐 It's essentially a shorthand for the following code:

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