JAVASCRIPT

Use Provide/Inject for Deep Component Communication in Vue 3

Master Vue 3's Provide/Inject to efficiently pass data down a deeply nested component hierarchy without prop drilling, maintaining clean code.

// src/App.vue
<template>
  <div>
    <h1>App Component</h1>
    <DeepComponentParent />
  </div>
</template>

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

const appMessage = ref('Hello from App!');
provide('appMessageKey', appMessage);
</script>

// src/components/DeepComponentParent.vue
<template>
  <div style="border: 1px solid blue; padding: 10px; margin: 5px;">
    <h2>Deep Component Parent</h2>
    <DeepComponentChild />
  </div>
</template>

<script setup>
import DeepComponentChild from './DeepComponentChild.vue';
</script>

// src/components/DeepComponentChild.vue
<template>
  <div style="border: 1px solid green; padding: 10px; margin: 5px;">
    <h3>Deep Component Child</h3>
    <p>Message from App: {{ injectedMessage }}</p>
    <button @click="changeMessage">Change App Message</button>
  </div>
</template>

<script setup>
import { inject } from 'vue';

const injectedMessage = inject('appMessageKey');

const changeMessage = () => {
  // If `injectedMessage` is a ref, its .value can be directly mutated
  // This demonstrates two-way communication if the provided value is reactive.
  if (injectedMessage && typeof injectedMessage.value !== 'undefined') {
    injectedMessage.value = 'Message changed from Child!';
  }
};
</script>
How it works: This snippet demonstrates Vue 3's `provide` and `inject` features for passing data down a component tree without manually passing props at each level (prop drilling). In `App.vue`, a reactive `appMessage` is `provide`d with a specific key. Any descendant component, regardless of its depth, can then `inject` this value using the same key. This example also shows how an injected reactive value can be mutated by the child component, reflecting changes back to the provider, enabling a form of two-way communication for deeply nested components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs