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

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

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!

[00:00] 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.

[00:20] 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.

[00:46] 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.

[01:09] 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.

[01:29] 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.

[01:53] 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.