View profile

Provide and Inject in Vue

Provide and Inject in Vue
By Mastering JS Weekly • Issue #59 • View online
Vue 2.6 introduced the provide/inject API to provide a cleaner way to avoid prop drilling. Vue 3 expanded the provide/inject API, letting you tie provide/inject in with reactivity.
Prop drilling is what happens when a component several levels down the component tree needs a property from a higher level component, but no intermediate component needs that prop. For example, in the below code, `level1` needs to have a `message` prop just to pass that prop to `level2`.

`message` is an example of prop drilling
`message` is an example of prop drilling
With `provide`, the top level `app` can define a reactive property `state` that the `level2` component can then pull in using `inject` as shown below.
`level2` accesses `message` with no involvement from `level1`
`level2` accesses `message` with no involvement from `level1`
The provide/inject API makes it easy to define a “long range prop” that’s fully reactive. Not only does `level2` get the initial `state`, but the template automatically updates when the top-level app’s state changes without any involvement from the `level1` component.
The provide/inject API is extremely powerful, and we’re making heavy use of it in our projects. Think Vuex modules, but without any outside modules. Each component can just listen to the part of the top-level state that it needs. The Vue docs have a great writeup about provide/inject.
Vue School has the best Vue 3 video course we've seen so far. Check it out!
Vue School has the best Vue 3 video course we've seen so far. Check it out!
Most Recent Tutorials
How to Check if a JavaScript Variable is Undefined - Mastering JS
How to use Axios' create() Method with POST Requests - Mastering JS
Axios Multipart Form Data - Mastering JS
How to Use the Select Tag with Vue - Mastering JS
Other Interesting Reads
The Magic of Provide/Inject in Vue.js | by Sandip Shrestha | Vue.js Developers | Medium
Designing Vue3 Plugins Using Provide and Inject – LearnVue
Did you enjoy this issue?
Mastering JS Weekly

A weekly summary of our tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue