Lzh on GitHub

节流一个 ref 值的改变。

Demo

使用

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

const input = shallowRef('')
const throttled = refThrottled(input, 1000)

尾随

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

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

const input = shallowRef('')
const throttled = refThrottled(input, 1000, false)

引导

允许回调函数立即被调用(在毫秒超时时间的引导边缘)。如果你不想要这种行为,将第四个参数设为 false(默认为 true):

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

const input = shallowRef('')
const throttled = refThrottled(input, 1000, undefined, false)

推荐阅读

类型声明

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>
export { refThrottled as throttledRef, refThrottled as useThrottle }