JAVASCRIPT

Global State Management with Vue 3 Provide/Inject

Implement simple global state management in Vue 3 using the Composition API's `provide` and `inject` functions for sharing reactive data across components without props drilling.

<!-- App.vue (Root Component) -->
<template>
  <div>
    <h1>App Component</h1>
    <p>Global Counter: {{ globalState.count }}</p>
    <button @click="incrementGlobal">Increment Global</button>
    <hr>
    <IntermediateComponent />
  </div>
</template>

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

// Define global state
const globalState = reactive({
  count: 0
});

const incrementGlobal = () => {
  globalState.count++;
};

// Provide the state and a method to update it
provide('globalStateKey', globalState);
provide('incrementGlobalKey', incrementGlobal);
</script>

<!-- IntermediateComponent.vue -->
<template>
  <div style="border: 1px solid green; padding: 10px; margin-top: 10px;">
    <h3>Intermediate Component</h3>
    <GrandchildComponent />
  </div>
</template>

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

<!-- GrandchildComponent.vue -->
<template>
  <div style="border: 1px solid red; padding: 10px; margin-top: 10px;">
    <h4>Grandchild Component</h4>
    <p>Injected Global Counter: {{ globalState.count }}</p>
    <button @click="incrementGlobal">Increment from Grandchild</button>
  </div>
</template>

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

// Inject the state and the method
const globalState = inject('globalStateKey');
const incrementGlobal = inject('incrementGlobalKey');

// Optional: handle cases where injection might fail (e.g., provide not found)
if (!globalState || !incrementGlobal) {
  console.error('Global state or increment function not provided!');
  // Handle error, e.g., provide default values or throw error
}
</script>
How it works: This snippet illustrates how to implement a basic global state management pattern in Vue 3 using the Composition API's `provide` and `inject`. The `App.vue` (root component) uses `provide` to make a reactive object (`globalState`) and a function (`incrementGlobal`) available to all its descendants. `GrandchildComponent.vue`, which is several levels deep, uses `inject` to retrieve and utilize this shared state and method without having to pass them down through props, effectively preventing 'prop drilling' in larger applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs