refThrottled
限制 ref 值的变化频率。
示例
此演示设置了 1000 毫秒的延迟。
节流后的值:
更新次数: 0
尾部触发: true
头部触发: false
用法
js
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
):
js
import { refThrottled } from '@vueuse/core'
import { shallowRef } from 'vue'
const input = shallowRef('')
const throttled = refThrottled(input, 1000, false)
头部触发
允许回调函数立即被调用 (在 ms
超时的头部)。如果你不想这种行为,可以将第四个参数设置为 false
(默认为 true
):
js
import { refThrottled } from '@vueuse/core'
import { shallowRef } from 'vue'
const input = shallowRef('')
const throttled = refThrottled(input, 1000, undefined, false)
推荐阅读
类型声明
typescript
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>
export { refThrottled as throttledRef, refThrottled as useThrottle }