Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript


    Vue 2.2 introduced a simple dependency injection system, allowing you to use provide and inject in your component options. This lesson shows you how to use them using the @Inject and @Provide decorators in tandem!



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Here we have a users component which renders a list of users, displaying their name, and an app component, which uses the users component. We are going to get those users from this URL, which is the REST API with fake data for these purposes.

    For that, we need some kind of HTTP library. For that, we can use Axios. Let's go and install Axios. Then we are going to import it here. Now, in the created hook, let's use the get method of Axios, pass in that URL, and then we see the result, which is inside of data to users.

    If we save this and run it, then we see the list of users displayed. There is something we can improve from our code. Right now, we are creating a hard dependency on Axios in a child component. That means that dependency is not easily replaceable, for example, for unit testing.

    We can improve that by using dependency injection. Let's take that dependency out to the app component, which is the parent one. In there, we can use the provide decorator in order to use the simple dependency injection system that Vue has. We inject the HTTP variant in there.

    Now, we can go back to user, and change Axios for HTTP. Now, we can use the inject decorator, naming that variable as we named it before. We need to import it. I forgot to write this here. If we run it again, we see it's working the same way it was working before.

    Another way we can inject this is by using a string. We can say here, my HTTP module, and in users, we need to use the same key. Instead of taking the variable name, now it's taking that string to manage the dependency. This still works.