JAVASCRIPT

Passing Data Deeply with Vue 3's Provide/Inject

Avoid prop drilling in Vue 3 by using the Provide/Inject API for efficient and clean data communication between deeply nested components.

// ParentComponent.vue
<template>
  <div>
    <h1>Parent Component</h1>
    <p>Shared Message from Parent: {{ parentMessage }}</p>
    <ChildComponent />
  </div>
</template>

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

const parentMessage = ref('Hello from the Parent!');

// Provide the message and a function to update it
provide('messageFromParent', parentMessage);
provide('updateParentMessage', (newMessage) => {
  parentMessage.value = newMessage;
});
</script>

// ChildComponent.vue
<template>
  <div style="border: 1px solid blue; padding: 10px; margin-left: 20px;">
    <h2>Child Component</h2>
    <GrandchildComponent />
  </div>
</template>

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

// GrandchildComponent.vue
<template>
  <div style="border: 1px solid green; padding: 10px; margin-left: 20px;">
    <h3>Grandchild Component</h3>
    <p>Received Message: {{ injectedMessage }}</p>
    <button @click="updateMessage('Updated from Grandchild!')">Update Parent Message</button>
  </div>
</template>

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

const injectedMessage = inject('messageFromParent', 'Default Message');
const updateParentMessage = inject('updateParentMessage');

const updateMessage = (newMessage) => {
  if (updateParentMessage) {
    updateParentMessage(newMessage);
  }
};
</script>
How it works: This example illustrates Vue 3's `provide` and `inject` API for passing data down a component tree without explicit prop drilling. The `ParentComponent` `provides` a reactive `messageFromParent` and an `updateParentMessage` function. The `GrandchildComponent`, nested two levels deep, can `inject` and use these values directly, enabling communication across distant components efficiently.

Need help integrating this into your project?

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

Hire DigitalCodeLabs