vue.joedoe.dev

← Totes les receptesComposables

Cercar sense atabalar: un ref amb debounce

Amb customRef el ref només avisa quan deixes d'escriure. Funciona amb v-model tal qual i el cercador no demana res a cada tecla.

TypeScript
import { customRef } from "vue";

/**
 * A ref that only tells the world it changed once you stop writing for `ms`.
 * Built on customRef, so v-model works on it as on any ref.
 */
export function useDebouncedRef<T>(initial: T, ms = 300) {
	let timer: ReturnType<typeof setTimeout> | undefined;
	let value = initial;
	return customRef<T>((track, trigger) => ({
		get() {
			track();
			return value;
		},
		set(next) {
			clearTimeout(timer);
			timer = setTimeout(() => {
				value = next;
				trigger();
			}, ms);
		},
	}));
}

Búsquedas hechas: 0

  • albaricoque
  • cereza
  • ciruela
  • fresa
  • granada
  • higo
  • kiwi
  • mango
  • melocotón
  • membrillo
  • naranja
  • pera

↑↓ moure's · ↵ obrir · esc tancar