Blog>
Snippets

Basic Provide/Inject in Vue.js 3 Components

Show how to pass data from a parent component to a deeply nested child component using the provide and inject options in a Vue.js 3 application.
// Parent component
Vue.component('parent-component', {
  provide() {
    // The data we want to provide to the nested child components
    return {
      providedMessage: 'Hello from Parent!'
    };
  },
  template: `<div>
    <child-component></child-component>
  </div>`
});
This is the parent component that uses the 'provide' option to pass 'providedMessage' data for its descendants.
// Child component
Vue.component('child-component', {
  template: `<div>
    <nested-child-component></nested-child-component>
  </div>`
});
This is the immediate child component in the hierarchy. It doesn't need to do anything special to pass the provide data on.
// Nested child component (deeply nested)
Vue.component('nested-child-component', {
  inject: ['providedMessage'], // Use 'inject' to receive the provided data
  template: `<div>{{ providedMessage }}</div>`
});
This is the deeply nested child component. It 'injects' the 'providedMessage' so it can be used within its template.