JAVASCRIPT
Sharing Global State with Provide and Inject
Learn to efficiently share state across deeply nested components in Vue 3 using the `provide` and `inject` API, avoiding prop drilling for cleaner code.
// main.js or App.vue setup
import { createApp, ref, provide } from 'vue';
import App from './App.vue';
const app = createApp(App);
// Global data to be provided
const user = ref({ name: 'Alice', email: '[email protected]' });
app.provide('globalUser', user); // Provide the reactive user object
app.mount('#app');
// --- In a parent component (e.g., App.vue) ---
// No need to explicitly provide here if provided globally in main.js
// If you want to provide different data from a parent:
// <script setup>
// import { provide, ref } from 'vue';
// const appConfig = ref({ theme: 'dark', language: 'en' });
// provide('appConfig', appConfig);
// </script>
// <template>
// <ChildComponent />
// </template>
// --- In a deeply nested child component ---
// UserDisplay.vue
<template>
<div>
<h3>User Details</h3>
<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>
<button @click="updateUserName">Update Name</button>
</div>
</template>
<script setup>
import { inject } from 'vue';
// Inject the global user object
const user = inject('globalUser');
const updateUserName = () => {
if (user) {
user.value.name = 'Bob Smith';
}
};
</script>
How it works: The `provide` and `inject` API in Vue 3 allows components to share data without explicit prop passing through every level of the component tree. A value is `provide`d by an ancestor component (or globally via `app.provide`), and then any descendant component, no matter how deep, can `inject` that value. This is particularly useful for global configurations, theme settings, or user data, acting as a lightweight dependency injection system. The provided value remains reactive if a `ref` or `reactive` object is provided.