Learn how to use the provide/ inject function pair with the Composition API to pass data into deeply nested components in Vue.js 3.
Usually, when we want to pass data from a parent to a child component, we use props. Vue.js has made this straightforward and easy to do. But we’ve probably experienced frustration at some point when we need to pass data from a parent-level component to a deeply nested child component.
If we were to use props, we would end up passing the data to each component on each level of the Vue component tree for the data to get to its final destination. This is called prop drilling and could cause our app to look more complex than it is. And if it were an application with a simple state, using Vuex in it would be overkill.
Luckily for us, Vue has the provide
/inject
API, and with the introduction of the Composition API in Vue 3, it has never been better.
Using the provide
and inject
pair, parent components can send data to their children components regardless of how deep the component hierarchy is. The parent component has a provide
function to supply data, and the child component has an inject
function to start using this data.
In the image above, we have three levels of children components. The data we want to pass is contained in the parent component, and the desired destination for the data is deeply nested in the third level of the component tree. We could achieve this using props, but at the expense of our code’s simplicity and readability. Let’s see how we can do this without sacrificing either.
First, we need to install the latest version of Vue CLI v4.5 with the command below:
yarn global add @vue/cli@next
#OR
npm install -g @vue/cli@next
The run the command below to create a new Vue app:
vue create provide-inject-tutorial
#vue #javascript #api