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);
},
}));
}<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useDebouncedRef } from "./useDebouncedRef";
const fruits = ["albaricoque", "cereza", "ciruela", "fresa", "granada", "higo", "kiwi", "mango", "melocotón", "membrillo", "naranja", "pera"];
const query = useDebouncedRef("", 400);
const searches = ref(0);
const found = computed(() => fruits.filter((f) => f.includes(query.value.toLowerCase())));
watch(query, () => searches.value++);
</script>
<template>
<input v-model="query" type="search" placeholder="Escribe deprisa: «me»…" />
<p class="muted">Búsquedas hechas: {{ searches }}</p>
<ul>
<li v-for="f in found" :key="f">{{ f }}</li>
</ul>
</template>Búsquedas hechas: 0
- albaricoque
- cereza
- ciruela
- fresa
- granada
- higo
- kiwi
- mango
- melocotón
- membrillo
- naranja
- pera