How to use provide and inject with the Composition API in Vue.js?
In the world of Vue.js, passing data between components can become a complicated task if you don't use the right tools. This is where provide
and inject
come into play, offering an elegant solution for sharing data between a component and its descendants. This mechanism avoids the need to manually pass data through each hierarchical level of a component, which could result in messy code and unnecessary props.
Implementation in Composition API
When using provide
and inject
with the Composition API, we must work within the setup
function. This is a significant change from the Options API, as we move from JSON configurations to functions that offer greater flexibility and readability.
Create provide in the main component
-
Configure setup: We start by creating the setup
function in the main component.
import { provide } from 'vue';
export default { setup() { provide('username', 'DianaNerd'); } }}
-
Define value: We use provide
to set a key-value pair, where 'username'
is the key to be shared with descendant components.
Receiving values in child components with inject
To receive the values provided in a child component, we use inject
, which must also be called inside the setup
function.
-
Import inject: We add inject
inside the import from Vue.
import { inject } from 'vue';
export default { setup() { const userName = inject('username');
return { userName };} }}
-
Access the values: we create a variable in setup
that receives the injected value, so that it is available in the component's template.
Reactivity in provide and inject
It is crucial to know that, by default, using provide
and inject
does not generate reactivity. To achieve this behavior, you will need to use tools like ref
when defining values in provide
. This will allow the values to be reactive and reflect changes automatically.
import { provide, ref } from 'vue';
export default { setup() { const username = ref('DianaNerd'); provide('username', username);
return { username }; } }}
Advantages of using Composition API
Switching from Options API to Composition API not only improves code organization, but also significantly reduces the number of lines required to perform the same operations. This approach not only improves code readability and maintainability, but also promotes a cleaner and more functional environment in Vue.js.
Recommendations
We encourage you to practice with provide
and inject
, applying reactivity and creating test projects. Experiment with use cases, such as a counter, to better understand these tools and their benefits in the data flow of your components. Share it with the community to get feedback!
Want to see more contributions, questions and answers from the community?