vue.joedoe.dev

Recetas

Composables y patrones que reutilizo en cada proyecto con Vue. Cada receta es un componente de verdad: el código que ves es el que está funcionando debajo.

Composables

Un ref que se guarda solo · su página

Preferencias, borradores, el último filtro… Aguanta recargas, se sincroniza entre pestañas y no rompe el render en servidor.

TypeScript
import { onMounted, onUnmounted, ref, watch, type Ref } from "vue";

/**
 * A ref that lives in localStorage: survives reloads and stays in sync
 * between tabs. Reads after mount, so server rendering never touches it.
 */
export function useLocalStorage<T>(key: string, initial: T): Ref<T> {
	const value = ref(initial) as Ref<T>;

	const read = () => {
		try {
			const saved = localStorage.getItem(key);
			if (saved !== null) value.value = JSON.parse(saved);
		} catch {
			/* Private mode or broken JSON: keep the initial value. */
		}
	};

	const onStorage = (event: StorageEvent) => {
		if (event.key === key) read();
	};

	onMounted(() => {
		read();
		window.addEventListener("storage", onStorage);
	});
	onUnmounted(() => window.removeEventListener("storage", onStorage));

	watch(
		value,
		(next) => {
			try {
				localStorage.setItem(key, JSON.stringify(next));
			} catch {
				/* Full or blocked: the ref still works for this visit. */
			}
		},
		{ deep: true },
	);

	return value;
}

Buscar sin machacar: un ref con debounce · su página

Con customRef el ref solo avisa cuando dejas de escribir. Funciona con v-model tal cual y el buscador no pide nada 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

Cargar datos sin respuestas cruzadas · su página

Vue 3.5+

Cargando, error y datos en un composable. Si cambias de disco antes de que llegue la respuesta, la petición vieja se cancela con onWatcherCleanup. Pasa rápido de uno a otro.

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++ };
}

Disco 1

Cargando…

El tamaño de un elemento, en vivo · su página

Vue 3.5+

Un ResizeObserver envuelto en composable y useTemplateRef para coger el elemento por su nombre.

TypeScript
import { onMounted, onUnmounted, ref, type Ref } from "vue";

/** The live width and height of an element, with a ResizeObserver. */
export function useElementSize(target: Readonly<Ref<HTMLElement | null>>) {
	const width = ref(0);
	const height = ref(0);
	let observer: ResizeObserver | undefined;

	onMounted(() => {
		if (!target.value) return;
		observer = new ResizeObserver(([entry]) => {
			width.value = Math.round(entry.contentRect.width);
			height.value = Math.round(entry.contentRect.height);
		});
		observer.observe(target.value);
	});
	onUnmounted(() => observer?.disconnect());

	return { width, height };
}

0 × 0

Arrastra la esquina. Con este ancho usaría una columna.

Componentes

v-model en tus componentes con defineModel · su página

Una línea en lugar de la prop modelValue, el emit update:modelValue y el computed que los unía.

Vue SFC
<script setup lang="ts">
const count = defineModel<number>({ default: 0 });
const { min = 0, max = 10 } = defineProps<{ min?: number; max?: number }>();
</script>

<template>
	<span class="stepper">
		<button :disabled="count <= min" aria-label="Menos" @click="count--">−</button>
		<output>{{ count }}</output>
		<button :disabled="count >= max" aria-label="Más" @click="count++">+</button>
	</span>
</template>

Adultos 2

Niños 0

Sois 2.

Un componente genérico con slots tipados · su página

generic="T" y defineSlots: la lista vale para cualquier cosa con id, y dentro del slot TypeScript sabe qué es cada item.

Vue SFC
<script setup lang="ts" generic="T extends { id: string | number }">
/*
 * One list for anything with an id: the parent decides how each item looks
 * through the #item slot, and TypeScript knows what `item` is in there.
 */
const { items } = defineProps<{ items: T[] }>();
const selected = defineModel<T | undefined>();

defineSlots<{
	item(props: { item: T; active: boolean }): unknown;
}>();
</script>

<template>
	<ul class="pick">
		<li v-for="item in items" :key="item.id">
			<button :aria-pressed="selected?.id === item.id" @click="selected = item">
				<slot name="item" :item="item" :active="selected?.id === item.id" />
			</button>
		</li>
	</ul>
</template>

Elige un disco

Desestructurar props sin perder la reactividad · su página

Vue 3.5+

Desde Vue 3.5 las props desestructuradas siguen siendo reactivas y los valores por defecto van ahí mismo. Adiós withDefaults().

Vue SFC
<script setup lang="ts">
import { computed, ref, watch } from "vue";

/*
 * Vue 3.5: destructured props stay reactive and take plain default values,
 * no withDefaults(). To watch one, wrap it in a getter.
 */
const { amount, currency = "EUR", locale = "es-ES" } = defineProps<{
	amount: number;
	currency?: string;
	locale?: string;
}>();

const text = computed(() => new Intl.NumberFormat(locale, { style: "currency", currency }).format(amount));

const changes = ref(0);
watch(
	() => amount,
	() => changes.value++,
);
</script>

<template>
	<output class="price">{{ text }}</output> <small>(cambios: {{ changes }})</small>
</template>
  • 24,90 € (cambios: 0)
  • $24.90 (cambios: 0)
  • ¥25 (cambios: 0)

Etiquetas e ids que siempre casan: useId · su página

Vue 3.5+

Un id único por instancia e igual en servidor y navegador. Para que cada label apunte a su input sin inventarse ids.

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>
Como quieras que te llamemos

Haz clic en una etiqueta: el foco va a su campo.

Reactividad

provide/inject con tipos y sin sorpresas · su página

Una InjectionKey lleva el tipo, y un useTheme() que avisa si falta el provide. Así no pasas props por cinco niveles.

TypeScript
import { inject, provide, ref, type InjectionKey, type Ref } from "vue";

type Theme = { mode: Ref<"light" | "dark">; toggle: () => void };

/* A Symbol key carries the type, so inject() knows what it gets back. */
const ThemeKey: InjectionKey<Theme> = Symbol("theme");

export function provideTheme() {
	const mode = ref<"light" | "dark">("light");
	const theme: Theme = { mode, toggle: () => (mode.value = mode.value === "light" ? "dark" : "light") };
	provide(ThemeKey, theme);
	return theme;
}

export function useTheme() {
	const theme = inject(ThemeKey);
	if (!theme) throw new Error("useTheme() needs a provideTheme() above it");
	return theme;
}

Este panel está en modo claro.

Y dentro hay un botón que no recibe ninguna prop:

Un computed que también se escribe · su página

Con get y set, un v-model puede ir a un valor derivado y repartirlo entre los refs de verdad.

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>

Nombre: Joe · Apellidos: Doe

Lo que trae Vue

Modal con Teleport y <dialog> · su página

Teleport lo saca a <body> y el <dialog> nativo pone el foco, el Esc y el fondo. Con SSR (Nuxt, Astro), teletranspórtalo solo tras montar: hidratar un Teleport a <body> puede romper la página entera, me pasó haciendo esta.

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>

Esta caja tiene overflow: hidden, y aun así el modal sale entero.

Listas que se reordenan con animación · su página

TransitionGroup con la clase -move: cada elemento se desliza a su nuevo sitio. Respeta «reducir movimiento».

Demo.vue
<script setup lang="ts">
import { ref } from "vue";

let next = 6;
const items = ref([1, 2, 3, 4, 5]);

const shuffle = () => (items.value = [...items.value].sort(() => Math.random() - 0.5));
const add = () => items.value.splice(Math.floor(Math.random() * (items.value.length + 1)), 0, next++);
const remove = (n: number) => (items.value = items.value.filter((i) => i !== n));
</script>

<template>
	<p>
		<button @click="shuffle">Barajar</button>
		<button @click="add">Añadir</button>
		<span class="muted">· clic en una para quitarla</span>
	</p>
	<TransitionGroup name="list" tag="ul" class="chips">
		<li v-for="n in items" :key="n" @click="remove(n)">{{ n }}</li>
	</TransitionGroup>
</template>

<style scoped>
.chips {
	position: relative;
	display: flex;
	flex-wrap: wrap;
	gap: 0.5rem;
	padding: 0;
	list-style: none;
}
.chips li {
	display: grid;
	place-items: center;
	width: 2.75rem;
	height: 2.75rem;
	border-radius: 10px;
	background: #42b883;
	color: #10261b;
	font-weight: 700;
	cursor: pointer;
}
/* Moving items glide to their new place; leaving ones fade out of the flow. */
.list-move,
.list-enter-active,
.list-leave-active {
	transition: all 0.4s ease;
}
.list-enter-from,
.list-leave-to {
	opacity: 0;
	transform: scale(0.5);
}
.list-leave-active {
	position: absolute;
}
@media (prefers-reduced-motion: reduce) {
	.list-move,
	.list-enter-active,
	.list-leave-active {
		transition: none;
	}
}
</style>

· clic en una para quitarla

  • 1
  • 2
  • 3
  • 4
  • 5

Pestañas que no pierden lo escrito · su página

KeepAlive guarda el componente en lugar de destruirlo, y onActivated/onDeactivated te dicen cuándo vuelve y cuándo se va.

Vue SFC
<script setup lang="ts">
import { onActivated, onDeactivated, ref } from "vue";

/* Inside KeepAlive the component isn't destroyed: it only pauses and resumes. */
const seconds = ref(0);
let timer: ReturnType<typeof setInterval> | undefined;

onActivated(() => (timer = setInterval(() => seconds.value++, 1000)));
onDeactivated(() => clearInterval(timer));
</script>

<template>
	<p>Llevas {{ seconds }} s en esta pestaña (se pausa al salir).</p>
</template>

↑↓ moverse · ↵ abrir · esc cerrar