JAVASCRIPT

Global State Sharing with Vue 3 Provide/Inject

Discover how Vue 3's Provide/Inject API simplifies sharing data across deeply nested components without prop drilling, enhancing component reusability.

// App.vue
<template>
  <div>
    <h1>App Root</h1>
    <ChildA />
  </div>
</template>

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

const appName = ref('My Super App');
const userSettings = ref({ theme: 'dark', notifications: true });

provide('appName', appName);
provide('userSettings', userSettings);

// You can also provide reactive objects directly
// provide('mutableSettings', userSettings); // If children should be able to modify
</script>

// components/ChildA.vue
<template>
  <div style="border: 1px solid blue; padding: 10px; margin: 10px;">
    <h2>Child A</h2>
    <ChildB />
  </div>
</template>

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

// components/ChildB.vue
<template>
  <div style="border: 1px solid green; padding: 10px; margin: 10px;">
    <h3>Child B</h3>
    <p>App Name from Inject: {{ appName }}</p>
    <p>User Theme from Inject: {{ userSettings.theme }}</p>
    <button @click="toggleTheme">Toggle Theme</button>
  </div>
</template>

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

const appName = inject('appName');
const userSettings = inject('userSettings'); // Injected as a reactive object

const toggleTheme = () => {
  userSettings.value.theme = userSettings.value.theme === 'dark' ? 'light' : 'dark';
};
</script>
How it works: Vue 3's `provide` and `inject` offer a dependency injection system for components. A parent component can `provide` values (reactive or static) using a key, and any descendant component, regardless of how deep, can `inject` those values using the same key. This avoids "prop drilling" where props have to be passed down through many intermediate components that don't directly use them, making component trees cleaner and more maintainable. In this example, `appName` and `userSettings` are provided at the root and injected by `ChildB` several levels down.

Need help integrating this into your project?

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

Hire DigitalCodeLabs