JAVASCRIPT
Implement Dependency Injection with Provide/Inject
Learn how to use Vue 3's `provide` and `inject` to pass data or functions deeply down a component tree without prop drilling, simplifying state management.
<!-- ParentComponent.vue -->
<template>
<div>
<h2>Parent Component</h2>
<p>Shared Message: {{ sharedMessage }}</p>
<ChildComponent />
</div>
</template>
<script setup>
import { ref, provide, readonly } from 'vue';
import ChildComponent from './ChildComponent.vue';
const sharedMessage = ref('Hello from Parent!');
const updateMessage = (newMessage) => {
sharedMessage.value = newMessage;
};
// Provide the ref (readonly) and a function to update it
provide('messageKey', readonly(sharedMessage));
provide('updateMessageKey', updateMessage);
</script>
<!-- ChildComponent.vue -->
<template>
<div style="border: 1px solid lightblue; padding: 10px; margin: 10px;">
<h3>Child Component</h3>
<GrandchildComponent />
</div>
</template>
<script setup>
import GrandchildComponent from './GrandchildComponent.vue';
</script>
<!-- GrandchildComponent.vue -->
<template>
<div style="border: 1px solid lightgreen; padding: 10px; margin: 10px;">
<h4>Grandchild Component</h4>
<p>Injected Message: {{ message }}</p>
<button @click="updateInjectedMessage('Updated from Grandchild!')">Update Message</button>
</div>
</template>
<script setup>
import { inject } from 'vue';
// Inject the provided values using their keys
const message = inject('messageKey');
const updateInjectedMessage = inject('updateMessageKey');
</script>
How it works: Vue 3's `provide` and `inject` offer a robust way to implement dependency injection, allowing data or functions to be passed from an ancestor component to any descendant component, regardless of how deep the component hierarchy is. The `provide` function makes data available using a specific key, and `inject` retrieves it. This avoids 'prop drilling' and makes complex component communication cleaner. Using `readonly()` with `provide` ensures that injected refs cannot be accidentally modified by descendant components, maintaining data integrity.