The Magic of Provide/Inject in Vue.js

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

Sandip Shrestha
Jun 21, 2019 · 2 min read

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.

Example:

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

A basic example of provide/inject

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

Injecting functions using provide/inject

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

Reactive binding in provide/inject

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

More on provide/inject on the official documentation here.


Vue.js Developers

Helping web professionals up their skill and knowledge of…

Sandip Shrestha

Written by

Programmer in the making and making programming fun in the process.

Vue.js Developers

Helping web professionals up their skill and knowledge of Vue.js

More From Medium

More from Vue.js Developers

More from Vue.js Developers

More from Vue.js Developers

Handling Events with Vue.js

More from Vue.js Developers

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade