Blog>
Snippets

Using provide and inject for dependency injection

Demonstrate the use of provide and inject for dependency injection with a comparison between utilizing them in the Options API versus the Composition API.
// Options API example

Vue.component('parent-component', {
  provide() {
    return {
      apiService: new ApiService(), // instance of some service
    };
  },
  // ... other options
});

Vue.component('child-component', {
  inject: ['apiService'],
  mounted() {
    console.log(this.apiService); // use the injected service
  },
  // ... other options
});
In the Options API, the 'provide' function defined within the parent component returns an object with the dependencies which then get injected into any descendant component through the 'inject' option. The 'child-component' assumes an ApiService is provided by an ancestor component and uses it.
// Composition API example

import { provide, inject } from 'vue';

const ParentComponent = {
  setup() {
    const apiService = new ApiService();
    provide('apiService', apiService);
    // setup logic
  },
  // ... other options
};

const ChildComponent = {
  setup() {
    const apiService = inject('apiService');
    if (apiService) {
      console.log(apiService); // use the injected service
    }
    // setup logic
  },
  // ... other options
};
In the Composition API, within the setup function of the 'ParentComponent', we call 'provide' to pass an instance of ApiService, identified by a key 'apiService'. In 'ChildComponent' we use 'inject' to access the ApiService provided by an ancestor component.