createContext() is a utility that helps create type-safe context providers and consumers in Vue components. It provides a way to share data between components without prop drilling, similar to React's Context API.
<script lang="ts"> tag, not in a <script setup lang="ts"> tag.import { createContext } from '~/utils/createContext';
// Create a context with a provider component name
const [injectMyContext, provideMyContext]
= createContext<MyContextType>('MyProvider');
// Or with multiple possible provider components
const [injectMyContext, provideMyContext]
= createContext<MyContextType>(['ProviderA', 'ProviderB']);
// Optional: Specify a custom context name
const [injectMyContext, provideMyContext]
= createContext<MyContextType>('MyProvider', 'CustomContextName');
Creates a context with type-safe provider and consumer functions.
| Prop | Default | Type |
|---|---|---|
providerComponentName* | string | string[]The name(s) of the component(s) that will provide the context | |
contextName | stringOptional custom name for the context (used in error messages) |
| Method | Type |
|---|---|
injectContext | () => ContextValueConsumes the context value from a provider component. |
provideContext | (contextValue: ContextValue) => voidProvides a context value to child components. |
Consumes the context value from a provider component. Returns the context value if found, otherwise returns the fallback value if provided.
Throws an error if the context is not found (component is not a child of the provider).
[error]: 'Injection "injectionKey" not found. Component must be used within "providerComponentName"'
| Prop | Default | Type |
|---|---|---|
fallback | TOptional fallback value to use if context injection fails |
Provides a context value to child components.
| Prop | Default | Type |
|---|---|---|
contextValue* | TThe value to provide to child components |
<script lang="ts">
import { createContext } from '~/utils/createContext';
export type ThemeContext = {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
export const [injectThemeContext, provideThemeContext]
= createContext<ThemeContext>("ThemeProvider");
</script>
<script setup lang="ts">
const theme = ref<'light' | 'dark'>('light');
const toggleTheme = () => {
theme.value = theme.value === 'light' ? 'dark' : 'light';
};
provideThemeContext({
theme: theme.value,
toggleTheme,
});
</script>
<script setup lang="ts">
import { injectThemeContext } from './ProviderComponent.vue';
const { theme, toggleTheme } = injectThemeContext();
</script>
The utility is fully type-safe: