JAVASCRIPT

Share Data Across Deeply Nested Components with Vue 3 provide and inject

Master Vue 3's `provide` and `inject` to pass data down through an arbitrary number of component levels without prop drilling, simplifying state management for distant descendants.

// ParentComponent.vue
<template>
  <div>
    <h2>Parent Component</h2>
    <button @click="incrementCount">Increment from Parent</button>
    <IntermediateComponent />
  </div>
</template>

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

const sharedCount = ref(0);
const sharedMessage = 'Hello from Parent!';

// Provide a reactive value and a static value
provide('countKey', sharedCount);
provide('messageKey', sharedMessage);

const incrementCount = () => {
  sharedCount.value++;
};
</script>

// IntermediateComponent.vue
<template>
  <div>
    <h3>Intermediate Component</h3>
    <ChildComponent />
  </div>
</template>

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

// ChildComponent.vue
<template>
  <div>
    <h4>Child Component</h4>
    <p>Received Count: {{ count }}</p>
    <p>Received Message: {{ message }}</p>
    <button @click="incrementCountFromChild">Increment from Child</button>
  </div>
</template>

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

// Inject the provided values using their keys
const count = inject('countKey');
const message = inject('messageKey');

const incrementCountFromChild = () => {
  // If the provided value is a ref, its value can be mutated
  if (count) {
    count.value++;
  }
};
</script>
How it works: Vue 3's `provide` and `inject` mechanism is designed for passing data down the component tree without having to manually pass props at every level (known as 'prop drilling'). A parent component uses `provide` to make data available with a specific key. Any descendant component, no matter how deep, can then use `inject` with the same key to access that data. This is particularly useful for global configurations, themes, or reactive states that need to be shared across many components without resorting to a full state management library.

Need help integrating this into your project?

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

Hire DigitalCodeLabs