JAVASCRIPT

Implementing `provide` and `inject` for Deep Dependency Injection

Master Vue 3's `provide` and `inject` to pass data down deeply nested components without prop drilling, improving component architecture and maintainability.

// App.vue (Parent component - Provider)
<template>
  <div style="border: 2px solid #007bff; padding: 20px;">
    <h1>App Component (Provider)</h1>
    <p>Parent App Name: {{ appName }}</p>
    <DeeplyNestedParent />
  </div>
</template>

<script setup>
import { provide, ref } from 'vue';
import DeeplyNestedParent from './components/DeeplyNestedParent.vue';

const appName = ref('My Awesome App');
const updateAppName = (newName) => {
  appName.value = newName;
};

// Provide a reactive value and a function
provide('appNameKey', appName); // Use a string key
provide('updateAppNameKey', updateAppName);
</script>

// components/DeeplyNestedParent.vue
<template>
  <div style="border: 1px solid #6c757d; padding: 15px; margin: 10px 0;">
    <h3>Deeply Nested Parent</h3>
    <AnotherNestedComponent />
  </div>
</template>
<script setup>
import AnotherNestedComponent from './AnotherNestedComponent.vue';
</script>

// components/AnotherNestedComponent.vue (Consumer)
<template>
  <div style="border: 1px solid #28a745; padding: 15px; margin: 10px 0;">
    <h4>Another Nested Component (Consumer)</h4>
    <p>Injected App Name: {{ injectedAppName }}</p>
    <button @click="changeName">Change App Name via Inject</button>
  </div>
</template>
<script setup>
import { inject } from 'vue';

// Inject the provided values using the same string keys
const injectedAppName = inject('appNameKey', 'Default App Name'); // With a default value
const updateAppName = inject('updateAppNameKey');

const changeName = () => {
  if (updateAppName) {
    updateAppName('Injected Update: ' + Math.random().toFixed(2));
  }
};
</script>
How it works: This code demonstrates Vue 3's `provide` and `inject` mechanism, a powerful alternative to prop drilling for passing data down through deeply nested component trees. A parent component `provide`s a value (which can be reactive), and any descendant component, regardless of how deep, can `inject` that value using the same injection key. This helps decouple components, allowing consumers to access shared data or functions without explicitly passing them through every intermediate component as props.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs