Blog>
Snippets

Using Provide/Inject with a Reactive Object

Provide a reactive object using Vue's reactive function and demonstrate how child components can react to its changes with the inject API.
import { reactive, provide, inject } from 'vue';

// In the parent component
export default {
  setup() {
    // Create a reactive object
    const state = reactive({
      count: 0
    });

    // Provide the reactive object to child components
    provide('sharedState', state);

    return { state };
  },
  // Rest of the component options
};
This code creates a reactive object in a parent component and uses Vue's 'provide' function to make it available to its child components.
// In a child component
export default {
  setup() {
    // Inject the reactive object provided by the parent component
    const sharedState = inject('sharedState');

    // Use the injected reactive object directly in the template
    // or within the setup function to react to its changes
    return { sharedState };
  },
  // Rest of the component options
};
This code in a child component uses Vue's 'inject' API to access the reactive object provided by the parent component and utilizes it within the component.