Subscribe on changes!

Using provide/inject in a directive

avatar
Nov 26th 2021

What problem does this feature solve?

Sometime you need to provide something from the root component, then the provide is really useful for this:

<MyApp>
   // This thing just provides something, like: provide('my-stuff', ...)
</MyApp>

And sometime you want to inject my-stuff into a directive:

const MyDirective: Directive = {
  created: (el, binding) => {
    inject('my-stuff')  // [Vue warn]: inject() can only be used inside setup() or functional components.
  }
}

For now you can't do that. And yes, there are many workarounds to solve this problem, but I think this, lets say, is the most decent way to perform.

Any possibility?

What does the proposed API look like?

const MyDirective: Directive = {
  created: (el, binding) => {
    const myStuff = inject('my-stuff')  // It works!
  }
}
avatar
May 26th 2023

why this not to do?

avatar
Jul 21st 2023

Any updates? In my application, I create smaller Vue apps for custom tooltips, and Inject API can significantly reduce the number of options I need to pass to my directive.