vue icon indicating copy to clipboard operation
vue copied to clipboard

Provide/inject for custom directives

Open ianwalter opened this issue 6 years ago • 32 comments

What problem does this feature solve?

If a user uses a custom directive in their app in multiple places they might need to configure the directive in two or more different ways depending on the area of the app in which the directive is being used. If this configuration is used in many instances in one of these areas, providing this configuration on every instance becomes redundant and cumbersome.

What does the proposed API look like?

I think the provide/inject pattern would be a good solution to this. A user could add different configurations in the top level provider components and use the custom directive normally in their descendants.

var Provider = {
  provide: {
    foo: 'bar'
  },
  // ...
}

var OtherProvider = {
  provide: {
    foo: 'baz'
  },
  // ...
}

Vue.directive('bar', {
  inject: ['foo'],
  bind (el, binding) {
    // binding.injections.foo or binding.foo 
  }
})
<provider><div v-bar="something"></div></provider>
<other-provider><div v-bar="somethingElse"></div></other-provider>

I'm not confident on what the best place is for the actual injections to live in the directive hook arguments but there are some ideas in the code example above.

ianwalter avatar Aug 31 '17 13:08 ianwalter