With customRef the ref only reports once you stop typing. It works with v-model as is, and search doesn't fire on every key.
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); }, }));}
Loading, error and data in one composable. If you switch record before the answer arrives, the old request is cancelled with onWatcherCleanup. Click through quickly.
TypeScript
import { onWatcherCleanup, ref, shallowRef, toValue, watch, type MaybeRefOrGetter } from "vue";/** * Loads data whenever its input changes, with loading and error states. * If the input changes mid-request, the old request is aborted (Vue 3.5's * onWatcherCleanup), so a slow old answer never overwrites a newer one. */export function useAsync<I, T>(input: MaybeRefOrGetter<I>, load: (input: I, signal: AbortSignal) => Promise<T>) { const data = shallowRef<T>(); const error = shallowRef<Error>(); const loading = ref(false); /* Bumped by reload(), so the same input can be asked for again. */ const attempt = ref(0); watch( [() => toValue(input), attempt], async ([value]) => { const controller = new AbortController(); onWatcherCleanup(() => controller.abort()); loading.value = true; error.value = undefined; try { data.value = await load(value, controller.signal); } catch (e) { if (!controller.signal.aborted) error.value = e as Error; } finally { if (!controller.signal.aborted) loading.value = false; } }, { immediate: true }, ); return { data, error, loading, reload: () => attempt.value++ };}
Vue SFC
<script setup lang="ts">import { ref } from "vue";import { useAsync } from "./useAsync";/* A pretend API: slow, and it fails now and then. */const fakeApi = (id: number, signal: AbortSignal) => new Promise<string>((resolve, reject) => { const timer = setTimeout(() => { if (Math.random() < 0.25) reject(new Error("El servidor se ha caído")); else resolve(`Ficha del disco nº ${id}`); }, 400 + Math.random() * 900); signal.addEventListener("abort", () => clearTimeout(timer)); });const id = ref(1);const { data, error, loading, reload } = useAsync(id, fakeApi);</script><template> <p> <button @click="id--" :disabled="id <= 1">←</button> Disco {{ id }} <button @click="id++">→</button> </p> <p v-if="loading" class="muted">Cargando…</p> <p v-else-if="error" class="error">{{ error.message }}. <button @click="reload">Otra vez</button></p> <p v-else>{{ data }}</p></template>
A unique id per instance, identical on server and browser. So every label points at its input without making ids up.
Vue SFC
<script setup lang="ts">import { useId } from "vue";/* * Vue 3.5: useId gives an id that is unique per instance and the same on the * server and in the browser, so label, input and hint always match. */const value = defineModel<string>({ default: "" });const { label, hint } = defineProps<{ label: string; hint?: string }>();const id = useId();</script><template> <div class="field"> <label :for="id">{{ label }}</label> <input :id="id" v-model="value" :aria-describedby="hint ? `${id}-hint` : undefined" /> <small v-if="hint" :id="`${id}-hint`">{{ hint }}</small> </div></template><style scoped>.field { display: grid; gap: 0.2rem; margin-bottom: 0.75rem;}small { opacity: 0.7;}</style>
Vue SFC
<script setup lang="ts">import { ref } from "vue";import Field from "./Field.vue";const name = ref("");const city = ref("Sant Sadurní d'Anoia");</script><template> <Field v-model="name" label="Nombre" hint="Como quieras que te llamemos" /> <Field v-model="city" label="Pueblo" /> <p class="muted">Haz clic en una etiqueta: el foco va a su campo.</p></template>
With get and set, a v-model can bind to a derived value and spread it across the real refs.
Demo.vue
<script setup lang="ts">import { computed, ref } from "vue";const first = ref("Joe");const last = ref("Doe");/* A computed with get and set: v-model writes the whole name, and the setter splits it. */const full = computed({ get: () => `${first.value} ${last.value}`.trim(), set(value: string) { const [head = "", ...rest] = value.split(" "); first.value = head; last.value = rest.join(" "); },});</script><template> <label>Nombre completo <input v-model="full" /></label> <p class="muted"> Nombre: <code>{{ first }}</code> · Apellidos: <code>{{ last }}</code> </p> <label>O solo el nombre <input v-model="first" /></label></template>
Teleport moves it to <body> and the native <dialog> brings focus, Esc and the backdrop. With SSR (Nuxt, Astro), only teleport after mounting: hydrating a Teleport into <body> can wreck the whole page, as it did while I built this one.
Vue SFC
<script setup lang="ts">import { onMounted, ref, useTemplateRef, watch } from "vue";/* * A native <dialog> moved to <body> with Teleport, so no parent's overflow * or z-index can trap it. showModal() brings focus trapping, Esc and the * backdrop for free. * * With server rendering (Nuxt, Astro…), teleport only after mounting: the * server's HTML has nothing in <body> to match, and hydrating a Teleport * there can wreck the page. */const open = defineModel<boolean>({ default: false });const { title } = defineProps<{ title: string }>();const dialog = useTemplateRef<HTMLDialogElement>("dialog");const mounted = ref(false);onMounted(() => (mounted.value = true));watch(open, (value) => { if (value) dialog.value?.showModal(); else dialog.value?.close();});</script><template> <Teleport v-if="mounted" to="body"> <dialog ref="dialog" class="modal" @close="open = false" @click.self="open = false"> <h2>{{ title }}</h2> <slot /> <form method="dialog"><button>Cerrar</button></form> </dialog> </Teleport></template><style scoped>.modal { max-width: min(90vw, 26rem); padding: 1.25rem 1.5rem; border: 0; border-radius: 14px; box-shadow: 0 20px 50px rgb(0 0 0 / 0.3);}.modal::backdrop { background: rgb(16 38 27 / 0.45);}.modal h2 { margin-top: 0;}</style>
Vue SFC
<script setup lang="ts">import { ref } from "vue";import Modal from "./Modal.vue";const open = ref(false);</script><template> <div class="trap"> <p class="muted">Esta caja tiene overflow: hidden, y aun así el modal sale entero.</p> <button @click="open = true">Abrir el modal</button> </div> <Modal v-model="open" title="Hola 👋"> <p>Pulsa Esc, haz clic fuera o usa el botón.</p> </Modal></template><style scoped>.trap { overflow: hidden; max-height: 7rem; padding: 0.75rem; border: 2px dashed #42b883; border-radius: 10px;}</style>