Vue: Allow defining optional inject dependency with default values

Created on 13 Jul 2017  ·  3Comments  ·  Source: vuejs/vue

What problem does this feature solve?

In case of components that can work both as standalone and as children, it would be nice to be able to provide default values for the not provided dependencies.
It would also avoid the warning for missing inject in case this is one of the expected use case.

What does the proposed API look like?

inject: Array | { [key: string]: string | Symbol | { name: string | Symbol, default: any } }

feature request in review

Most helpful comment

I'm working on a component library that utilizes provide and inject for certain components to behave/look slightly differently when in the context of another component of the library. Since our components are used by other engineers for development, warnings that the injection was not found keeps showing up in their environment.

Would love this feature to be implemented. And to add to it, as mentioned in https://github.com/vuejs/vue/issues/6137, I'd like to see a required attribute to indicate whether an injection is required or optional.

All 3 comments

Ditto on this request. What I typically find myself doing is overriding the injected property as data in order to provide a default:

inject: [
  'foo'
],
data () {
  return {
    foo: this.foo || 'default'
  }
}

I'm also +1 for this feature. Currently I have components that are nested within each other and parents provide info to the children. The warning always pops up for the root component as it doesn't have a provider for the injected property.

Specific use case: nested layout splitters.

I'm working on a component library that utilizes provide and inject for certain components to behave/look slightly differently when in the context of another component of the library. Since our components are used by other engineers for development, warnings that the injection was not found keeps showing up in their environment.

Would love this feature to be implemented. And to add to it, as mentioned in https://github.com/vuejs/vue/issues/6137, I'd like to see a required attribute to indicate whether an injection is required or optional.

Was this page helpful?
0 / 5 - 0 ratings