Vue3 Fundamentals ยท Composition & Reuse

Provide and inject

Provide and inject

Passing a value down a deep tree means threading it through every component in between. The middle components do not use the value; they only forward it. That is prop-drilling, and it makes every layer depend on a prop it does not need.

provide and inject skip the middle. An ancestor provides a value under a key, and any descendant injects that key:

<!-- the ancestor -->
<script setup>
import { provide } from 'vue';
provide('theme', 'dark');
</script>
<!-- a descendant, any depth below -->
<script setup>
import { inject } from 'vue';
const theme = inject('theme');
</script>

The descendant reaches the value without a prop in sight. The key is a string here, but it can be a symbol for safety. inject takes a second argument as a fallback for when no ancestor provided the key.

The Test mounts your component inside a parent that provides theme, and checks that your component renders the provided value. The starter hard-codes its own value, so the Test fails. Read the key with inject in App.vue.

Challenge

A parent provides a value under the theme key, but the component ignores it and shows its own. Export an App component from App.vue that reads the key with inject('theme') and renders the value in an <h1>.

The Test mounts your component inside a parent that provides theme and checks the rendered heading. The starter hard-codes light, so the Test fails. Inject the key instead.

App.vue
<script setup>
const theme = 'light';
</script>

<template>
  <h1>{{ theme }}</h1>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.