Memulai
Siklus Hidup
Peramban
Pengembangan
Paket Luar
useThrottle
Salinan sebuah nilai yang diperbarui paling sering sekali per jeda.
Langsung: 50
Dijatah 500 ms: 50
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.
Pemasangan
npx 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 terjatah = ref(toValue(value)) as Ref<T>
const { run, cancel } = useThrottleFn(
(baru: T) => {
terjatah.value = baru
},
wait,
options,
)
watch(() => toValue(value), baru => run(baru))
if (getCurrentScope())
onScopeDispose(cancel)
return terjatah
}API
ts
export function useThrottle<T>(
value: MaybeRefOrGetter<T>,
wait: MaybeRefOrGetter<number> = 1000,
options?: UseThrottleFnOptions,
)