JAVASCRIPT

Deep Dependency Injection with `provide` and `inject` in Vue 3

Master Vue 3's `provide` and `inject` to pass data or services down the component tree without prop drilling, simplifying complex component hierarchies.

// App.vue (Provider)
<template>
  <div>
    <h1>App Component</h1>
    <GrandparentComponent />
  </div>
</template>

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

const appName = ref('My Vue App');
const version = ref(3.2);

// Provide reactive data, optionally readonly
provide('appName', readonly(appName));
provide('version', version);

// You can also provide a function
const updateAppName = (newName) => {
  appName.value = newName;
};
provide('updateAppName', updateAppName);

// Example of providing an object with multiple values
provide('appSettings', {
  theme: 'dark',
  language: ref('en')
});
</script>

// GrandparentComponent.vue (just passes through)
<template>
  <div class="grandparent">
    <h2>Grandparent Component</h2>
    <ParentComponent />
  </div>
</template>
<script setup>
import ParentComponent from './ParentComponent.vue';
</script>

// ParentComponent.vue (just passes through)
<template>
  <div class="parent">
    <h3>Parent Component</h3>
    <ChildComponent />
  </div>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
</script>

// ChildComponent.vue (Consumer)
<template>
  <div class="child">
    <h4>Child Component</h4>
    <p>App Name: {{ providedAppName }}</p>
    <p>App Version: {{ providedVersion }}</p>
    <p>Theme: {{ appSettings.theme }}</p>
    <p>Language: {{ appSettings.language }}</p>
    <button @click="callUpdateAppName('New App Name')">Update App Name</button>
  </div>
</template>

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

// Inject provided values
const providedAppName = inject('appName', 'Default App'); // Second arg is default value
const providedVersion = inject('version');
const callUpdateAppName = inject('updateAppName');
const appSettings = inject('appSettings');
</script>
How it works: This snippet illustrates Vue 3's `provide` and `inject` functions for dependency injection. It allows a parent component to provide data or functions that can be injected by any descendant component, regardless of how deep they are nested, without resorting to prop drilling. It shows providing reactive values, functions, and objects, demonstrating a powerful pattern for managing global or semi-global dependencies.

Need help integrating this into your project?

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

Hire DigitalCodeLabs