vue.joedoe.dev

← Todas las recetasReactividad

provide/inject con tipos y sin sorpresas

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:

↑↓ moverse · ↵ abrir · esc cerrar