JAVASCRIPT

Vue 3: Deep Component Communication with `provide` and `inject`

Efficiently pass data down through deeply nested components in Vue 3 without prop drilling by utilizing the `provide` and `inject` features.

// App.vue (Parent Component)
<template>
  <div>
    <h1>App Component</h1>
    <ChildComponent />
  </div>
</template>

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

const appMessage = ref('Hello from App!');
provide('messageKey', appMessage); // Provide a reactive ref

const updateMessage = () => {
  appMessage.value = 'Updated message from App!';
};
provide('updateMessageKey', updateMessage); // Provide a function

</script>

// ChildComponent.vue
<template>
  <div>
    <h2>Child Component</h2>
    <GrandchildComponent />
  </div>
</template>

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

// GrandchildComponent.vue
<template>
  <div>
    <h3>Grandchild Component</h3>
    <p>Message from App: {{ injectedMessage }}</p>
    <button @click="callUpdateMessage">Update App Message</button>
  </div>
</template>

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

const injectedMessage = inject('messageKey');
const updateAppMessage = inject('updateMessageKey');

const callUpdateMessage = () => {
  if (updateAppMessage) {
    updateAppMessage();
  }
};
</script>
How it works: This example demonstrates `provide` and `inject` in Vue 3, a powerful mechanism for communicating between components that are not directly parent-child. A parent component can `provide` a value (which can be reactive, like a `ref`, or a function) using a unique key. Any descendant component, regardless of how deep, can then `inject` that value using the same key. This effectively solves 'prop drilling' by allowing data to be passed down the component tree without explicitly passing it through every intermediate component.

Need help integrating this into your project?

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

Hire DigitalCodeLabs