Limitations

Vue's dependency injection constructs help decouple your components, but there are some drawbacks that you should be aware of. Some of them can be mitigated, but others cannot.

For starters, Vue's injection feature works by matching the provider key with the one that was requested when injecting. This means that if you use the same injection key for multiple providers in the ancestor's chain of a component, then you'll shadow providers who are higher in the hierarchy. In practice, the last writer wins (that is, the provider closest to the injection point will be used). This is a drawback because it could cause surprises. We will address this issue in the next section.

Another limitation to consider is that the provide and inject bindings are (intentionally) not reactive, which means that changes won't be tracked by Vue, apart from if you inject objects that have already been observed by Vue's change tracking system: https://vuejs.org/v2/guide/reactivity.html.

One more drawback of Vue's DI support is that it cannot perform constructor injection. This is problematic with TypeScript because it means that our component class properties won't be fully initialized by the constructor, but set afterward. We'll see how we can work our way around this issue by leveraging TypeScript's definite assignment assertions, later in this book.

Moreover, Vue's DI support, since it's quite rudimentary, can only perform simple bindings between a provider and an injection point. If you have multiple implementations of a given interface, then the only way to distinguish those with regard to Vue's DI system is to create separate providers and have the client code be aware of those.

Finally, it is only possible to leverage this DI support from within Vue components, which means that you cannot wire other elements, such as services.

These limitations truly mean that we can't do pure dependency injection with Vue; we can only do basic things. Not all hope is lost, though, as future versions of Vue may improve this situation. Meanwhile, we can counter some of these limitations. Let's see how!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.196.182