inject()

Retrieves a value provided by an ancestor component.

Since Vue 3.0 Spec ↗

Syntax

inject<T>(key, defaultValue?, treatDefaultAsFactory?): T | undefined

Parameters

NameTypeRequiredDescription
key InjectionKey<T> | string No The key matching a provided value.
defaultValue T No Fallback when no provider is found.

Returns

T | undefined — The injected value or the default.

Examples

<script setup lang="ts">
import { inject } from 'vue';
import { ThemeKey } from './ThemeProvider.vue';

const theme = inject(ThemeKey, { dark: false });
</script>

<template>
  <div :class="{ dark: theme.dark }"><slot /></div>
</template>

Notes

inject must run synchronously during setup. Provide a default value (or a factory with the third arg true) to make the dependency optional. Pair with a typed InjectionKey for full type inference. The injected value stays reactive if the provider supplied a ref/reactive.