Sitemap
Vue.js Developers

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

The Magic of Provide/Inject in Vue.js

2 min readJun 21, 2019

--

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 VueForm the component is passing down an errors variable down to TextInput component.

A basic example of provide/inject

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

Injecting 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.

Reactive binding in provide/inject

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.

--

--

Vue.js Developers
Vue.js Developers

Published in Vue.js Developers

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

Sandip Shrestha
Sandip Shrestha

Written by Sandip Shrestha

I am a Software Engineer under construction and a hobbyist writer who writes about Software Development and the constant rambling thoughts inside my head.

Responses (1)