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;
}<script setup lang="ts">
import { useTheme } from "./theme";
/* Three levels down, and no props passed through the middle. */
const { mode, toggle } = useTheme();
</script>
<template>
<button @click="toggle">{{ mode === "light" ? "🌙 Oscuro" : "☀️ Claro" }}</button>
</template><script setup lang="ts">
import { provideTheme } from "./theme";
import ThemeButton from "./ThemeButton.vue";
const { mode } = provideTheme();
</script>
<template>
<div class="panel" :class="mode">
<p>Este panel está en modo {{ mode === "light" ? "claro" : "oscuro" }}.</p>
<div class="inner">
<p>Y dentro hay un botón que no recibe ninguna prop:</p>
<ThemeButton />
</div>
</div>
</template>
<style scoped>
.panel {
padding: 1rem;
border-radius: 10px;
transition: background 0.3s, color 0.3s;
}
.light {
background: #f3f7f5;
color: #213547;
}
.dark {
background: #213547;
color: #e8f3ee;
}
.inner {
padding: 0.75rem;
border: 1px dashed currentColor;
border-radius: 8px;
}
</style>Este panel está en modo claro.
Y dentro hay un botón que no recibe ninguna prop: