Before the existence of these wonderful helpers provide / inject from the vue3 composition apis, if we have to pass props from a top-level component to the child-level components, we have to ensure that the props are passed all the way down or we should rely on state managers like vuex to avoid passing props.
But these new helpers allow us to consume the props in the child components easily from the parent component without passing them redundantly.
Let's look at the below example where the parent component provides the title prop and the child component utilizes the title prop by simply injecting it.
// article-component.vue (ancestor)
import { ref, provide } from 'vue';
....
setup() {
const title = ref('Article Title');
provide('title', title);
}
// article-title-component.vue (child)
import { ref, inject } from 'vue';
....
setup() {
const title = inject('title');
return {
title
}
}
And what if the child component wants to update the injected prop? Let's provide the update callback as well.
// article-component.vue (ancestor)
import { ref, provide } from 'vue';
....
setup() {
const title = ref('Article Title');
provide('title', title);
provide('updateTitle', (newTitle) => title.value = newTitle);
}
// article-title-component.vue (child)
import { ref, inject } from 'vue';
....
setup() {
const title = inject('title');
const updateTitle = inject('updateTitle');
updateTitle(`Draft: ${title}`);
}
See, that's why it's a bliss!
PS: Used https://www.figma.com/figjam/ for the quick flow diagrams.
Top comments (0)