Considering incorporating Vue's new provide/inject feature into a project, I came across a warning in the official Vue documentation:
The documentation states that provide and inject are primarily intended for advanced plugin/component library usage. It is strongly discouraged to implement them in generic application code.
Despite this cautionary note, the reasoning behind it is not clearly articulated. What specific risks are associated with utilizing provide and inject in "generic application code" rather than in "advanced plugin/component library use cases"?
In the provided example:
// parent component providing 'foo'
var Provider = {
provide: {
foo: 'bar'
},
// ...
}
// child component injecting 'foo'
var Child = {
inject: ['foo'],
created () {
console.log(this.foo) // => "bar"
}
// ...
}
It seems that the main advantage lies in simplifying the process of passing data through nested components, allowing direct access to injected values in grandchild components without manually passing props down each level.
Additionally, it is possible to make the injected value reactive by deviating from the default non-reactive behavior when passing down an observed object. In this case, a warning would be warranted, as using reactive objects across nested components goes against conventional data flow practices and could potentially lead to confusion when tracking changes.