Blog>
Snippets

Combining Provide/Inject with the Composition API

Integrate provide/inject pattern within the setup function of the Composition API, illustrating the sharing of state between components.
// ParentComponent.vue
import { provide, reactive } from 'vue';

export default {
  setup() {
    // Define reactive state to be provided to child components
    const state = reactive({
      message: 'Hello from parent!'
    });

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

    return { state };
  }
};
This is the ParentComponent which uses the `provide` function from Vue's Composition API to provide a reactive state object to all of its child components.
// ChildComponent.vue
import { inject } from 'vue';

export default {
  setup() {
    // Inject the state provided by the parent component
    const sharedState = inject('sharedState');

    return { sharedState };
  }
};
This is the ChildComponent which uses the `inject` function from Vue's Composition API to inject the shared state provided by the parent.
<template>
  <div>
    <p>{{ sharedState.message }}</p>
  </div>
</template>

<script>
// Rest of the ChildComponent script...
</script>
This is the template of ChildComponent, which uses the injected `sharedState` to display the provided message.
<template>
  <div>
    <ChildComponent />
  </div>
</template>

<script>
// Rest of the ParentComponent script...
</script>
This is the template of ParentComponent, which includes the ChildComponent.