Dependency Injection in vuejs, Vue Cli Single Page Application


We can use DI in vuejs application by very simple way, using the @Provide and @Inject property decorator.So here is the scenario you have a service and you need the instance of the same in different component in normal way you have to create the instance of the same in different components and use it there.

But using DI you can use the @Provide property decorator and declare it in your App.vue and then you can reuse it in the components wherever you want by using the @Inject property decorator

In App.vue

    import {Component, Provide, Vue} from 'vue-property-decorator';
    @Component({
    })
    export default class App extends Vue {
           @Provide('vueApiServices')
           public vueApiServices = new VueApiServices();
     }
In your corresponding component

import { Vue, Prop, Component, Inject } from 'vue-property-decorator';
import {VueApiServices} from '../../services/VueApiServices';
@Component({
    components: {},
})
export default class InventoryDetailsComponent extends Vue {

@Inject('vueApiServices')
private vueApiService!: VueApiServices;
}



0 comments: