Blog>
Snippets

Basic Provide/Inject in Component Hierarchy

Define a provide option in the root component to share data with all descendants, using inject in the child components to utilize the shared data.
Vue.component('root-component', {
  provide: {
    sharedData: 'This data is shared with descendants'
  },
  template: `<div><child-component></child-component></div>`
});
Defines the root component with a provide option that contains the data to be shared with all of its descendants.
Vue.component('child-component', {
  inject: ['sharedData'],
  mounted() {
    console.log(this.sharedData); // This will log the injected data
  },
  template: `<div>{{ sharedData }}</div>`
});
Defines a child component that injects the sharedData from its ancestor components. It logs the injected data on mount and also renders it.