The Magic of Provide/Inject

The Magic of Provide/Inject in Vue.js

Dependency Injection in Vue.js will be a breeze with Provide and Inject duo

Often times is overwhelming to look at a larger component as a whole because there may be too much going on, breaking things down allows us to simplify a complex problem and focus our attention in more manageable pieces. One obvious complication of breaking down a large component is data flow and management.

Provide and Inject are used together to allow an ancestor component to serve as a dependency injector for all its descendants, regardless of how deep the component hierarchy is, as long as they are in the same parent chain.


For example, a parent component can inject validation messages in input components. Below is an example where the VueForm the component is passing down an errors variable down to TextInput component.

You can also provide and inject a function. The below example demonstrates passing getError() and setError() functions using provide/inject.

Note: the provide and inject bindings are NOT reactive. This is intentional. However, if you pass down an observed object, properties on that object do remain reactive.

Injections are available in props and data. So, you could set prop defaults to injected data or you can use injections as initial data.

More on provide/inject on the official documentation here.

If you enjoyed this article, please clap and share it with friends.

— — — — — — — — — — — — — You can also — — — — — — — — — — — — —

Read my other posts,

The Magic of Provide/Inject was originally published in Vue.js Developers on Medium, where people are continuing the conversation by highlighting and responding to this story.

You may also like...