跳到主要内容

refThrottled

分类
导出大小
534 B
上次更改
上个月
别名
useThrottlethrottledRef
相关

节流 ref 值的变化。

演示

此演示的延迟设置为 1000 毫秒。

节流

更新次数:0

尾部执行: true

立即执行: false

用法

ts
import { 
refThrottled
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
input
=
shallowRef
('')
const
throttled
=
refThrottled
(
input
, 1000)

一个对象 ref 的示例。

js
import { refThrottled } from '@vueuse/core'
import { shallowRef } from 'vue'

const data = shallowRef({
  count: 0,
  name: 'foo',
})
const throttled = refThrottled(data, 1000)

data.value = { count: 1, name: 'foo' }
console.log(throttled.value) // { count: 1, name: 'foo' } (immediate)

data.value = { count: 2, name: 'bar' }
data.value = { count: 3, name: 'baz' }
data.value = { count: 4, name: 'qux' }
console.log(throttled.value) // { count: 1, name: 'foo' } (still first value)

// After 1000ms, next change will be applied
await sleep(1100)
data.value = { count: 5, name: 'final' }
await nextTick()
console.log(throttled.value) // { count: 5, name: 'final' } (updated)

尾部执行

如果你不想监听尾部变化,请将第三个参数设置为 false(默认为 true

ts
import { 
refThrottled
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
input
=
shallowRef
('')
const
throttled
=
refThrottled
(
input
, 1000, false)

立即执行

允许回调函数立即调用(在 ms 超时时间的开始)。如果你不需要此行为,请将第四个参数设置为 false(默认为 true

ts
import { 
refThrottled
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
input
=
shallowRef
('')
const
throttled
=
refThrottled
(
input
, 1000,
undefined
, false)

类型声明

ts
export type 
RefThrottledReturn
<
T
= any> =
Ref
<
T
>
/** * Throttle execution of a function. Especially useful for rate limiting * execution of handlers on events like resize and scroll. * * @param value Ref value to be watched with throttle effect * @param delay A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful. * @param trailing if true, update the value again after the delay time is up * @param leading if true, update the value on the leading edge of the ms timeout */ export declare function
refThrottled
<
T
= any>(
value
:
Ref
<
T
>,
delay
?: number,
trailing
?: boolean,
leading
?: boolean,
):
RefThrottledReturn
<
T
>
/** @deprecated use `refThrottled` instead */ export declare const
throttledRef
: typeof
refThrottled
/** @deprecated use `refThrottled` instead */ export declare const
useThrottle
: typeof
refThrottled

来源

源代码演示文档

贡献者

Anthony Fu
Anthony Fu
Vida Xie
SerKo
IlyaL
Robin
Thimo Sietsma
IlyaL
Danny Feliz

更新日志

e5f74 - feat!: 弃用别名导出,转而使用原始函数名称 (#5009)
v13.1.0
c1d6e - feat(shared): 确保返回类型存在 (#4659)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。