Skip to content

refThrottled

类别
导出体积
534 B
上次更改
6 minutes ago
别名
useThrottlethrottledRef
相关

限制 ref 值的变化频率。

示例

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

节流后的值:

更新次数: 0

尾部触发: true

头部触发: false

用法

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

一个带有对象引用的示例。

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
>
/** * 函数节流,特别适用于限制像 resize 和 scroll 这样的事件处理程序的执行频率。 * * @param value 要使用节流效果监视的 Ref 值 * @param delay 以毫秒为单位的延迟时间,必须是大于或等于零的值。对于事件回调,最有用的值通常在 100 或 250(甚至更高)左右。 * @param trailing 如果为 true,在延迟时间结束后再次更新值 * @param leading 如果为 true,在 ms 超时的头部立即更新值 */ 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!: deprecate alias exports in favor of original function names (#5009)
c1d6e - feat(shared): ensure return types exists (#4659)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)