JAVASCRIPT

Simple Global State Management with Vue 3's Provide/Inject

Discover how to share reactive state across deeply nested components in Vue 3 using the provide and inject API, ideal for configuration data or application-wide settings.

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

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

const appSettings = reactive({
  theme: 'light',
  fontSize: '16px',
});

// Provide the reactive settings object to all descendants
provide('appSettingsKey', appSettings);

// You could also provide a method to update settings
provide('updateTheme', (newTheme) => {
  appSettings.theme = newTheme;
});
</script>

// ChildComponent.vue (Consumer)
<template>
  <div :style="{ backgroundColor: currentTheme.theme === 'dark' ? '#333' : '#eee', color: currentTheme.theme === 'dark' ? '#eee' : '#333', fontSize: currentTheme.fontSize }">
    <h2>Child Component</h2>
    <p>Current Theme: {{ currentTheme.theme }}</p>
    <p>Font Size: {{ currentTheme.fontSize }}</p>
    <button @click="toggleTheme">Toggle Theme</button>
  </div>
</template>

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

// Inject the provided settings and update method
const appSettings = inject('appSettingsKey');
const updateTheme = inject('updateTheme');

// Use a computed property if you want to expose a read-only version or derive values
const currentTheme = computed(() => appSettings);

const toggleTheme = () => {
  const newTheme = appSettings.theme === 'light' ? 'dark' : 'light';
  if (updateTheme) {
    updateTheme(newTheme);
  }
};
</script>

<style scoped>
div {
  padding: 20px;
  margin: 10px;
  border: 1px solid #ccc;
  border-radius: 8px;
}
button {
  margin-top: 10px;
  padding: 8px 15px;
  cursor: pointer;
}
</style>
How it works: Vue 3's `provide` and `inject` offer a way to pass data down the component tree without prop drilling, which is useful for global state management in simpler applications. The `App.vue` component uses `provide('appSettingsKey', appSettings)` to make a reactive object `appSettings` available to all its descendants. It also provides a function to update the theme. The `ChildComponent.vue` then uses `inject('appSettingsKey')` to access these settings. Changes to the `appSettings` object in the provider component will reactively update all consuming components, demonstrating a simple yet powerful way to manage shared state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs