主题
watchDebounced
防抖监听。回调函数只有在源停止变化达到指定时间后才会被调用。
🌐 Debounced watch. The callback will only be invoked after the source stops changing for the specified duration.
示例
用法
🌐 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
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
debounce | MaybeRefOrGetter<number> | 0 | 防抖延迟(毫秒,可响应) |
maxWait | MaybeRefOrGetter<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 }),
},
)