Blog>
Snippets

Provide/Inject with Composition API

Provide an example of using the provide and inject functions inside the setup function when working with the Composition API in Vue.js 3.
import { provide, inject, ref } from 'vue';

// In a parent component
export default {
  setup() {
    // Using ref to make the data reactive
    const sharedState = ref('This is a shared state');

    // Provide 'sharedState' to descendant components
    provide('sharedKey', sharedState);

    // Other setup logic ...

    return { sharedState };
  }
};
This code snippet represents a parent component using the Composition API. It creates a reactive reference using `ref` and then provides it to all descendant components using the `provide` function with a key 'sharedKey'.
import { inject } from 'vue';

// In a descendant component
export default {
  setup() {
    // Inject 'sharedState' from an ancestor component
    const sharedState = inject('sharedKey');

    // If the provided value could be possibly undefined
    // const sharedState = inject('sharedKey', defaultValue);

    // Other setup logic ...

    return { sharedState };
  }
};
This code snippet is for a descendant component that needs access to the 'sharedState' provided by an ancestor component. It uses the `inject` function with the key 'sharedKey' to access the provided state. If there's a chance the provided value is not available, you can provide a default value using `inject('sharedKey', defaultValue)`. The injected 'sharedState' can then be used within this component.