DEV Community

prakash chokalingam
prakash chokalingam

Posted on

Codebytes: provide / inject is a bliss in vue3

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.

old way

But these new helpers allow us to consume the props in the child components easily from the parent component without passing them redundantly.

new way

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
  }
}
Enter fullscreen mode Exit fullscreen mode

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}`);
}
Enter fullscreen mode Exit fullscreen mode

See, that's why it's a bliss!

PS: Used https://www.figma.com/figjam/ for the quick flow diagrams.

Top comments (0)