Pasangan useDebounce, untuk kasus sebaliknya: nilai yang berubah terus menerus dan tidak akan pernah "berhenti" — posisi pointer, jarak scroll, ukuran jendela. Debounce di sana tidak pernah memicu apa pun sampai gerakannya berhenti; throttle tetap memberi kabar sepanjang jalan.
Installation
pnpm dlx shadcn-vue@latest add @kliping/use-throttle Perlu @kliping terdaftar di components.json project Anda. Lihat cara menyiapkannya.
Ikut terpasang sendiri: use-throttle-fn.
Salin dulu use-throttle-fn — masing-masing memuat sumbernya di halamannya sendiri — lalu tempel berkas ini.
ts
import { getCurrentScope, onScopeDispose, ref, toValue, watch } from 'vue'
import type { MaybeRefOrGetter, Ref } from 'vue'
import { useThrottleFn } from '@/composables/use-throttle-fn'
import type { UseThrottleFnOptions } from '@/composables/use-throttle-fn'
export function useThrottle<T>(
value: MaybeRefOrGetter<T>,
wait: MaybeRefOrGetter<number> = 1000,
options?: UseThrottleFnOptions,
) {
const throttled = ref(toValue(value)) as Ref<T>
const { run, cancel } = useThrottleFn(
(next: T) => {
throttled.value = next
},
wait,
options,
)
watch(
() => toValue(value),
(next) => run(next),
)
if (getCurrentScope()) onScopeDispose(cancel)
return throttled
}API
ts
export function useThrottle<T>(
value: MaybeRefOrGetter<T>,
wait: MaybeRefOrGetter<number> = 1000,
options?: UseThrottleFnOptions,
)