What Is Provide / Inject in Vue?

In Vue, the provide and inject options pass data between components that are nested deep in the component tree. They are especially helpful in large, complex applications, where data has to reach components that are not in a direct parent-child relationship. They work together with Vue's reactivity and give you a strong way to manage data flow.
Provide
The provide option makes data or methods available to a component's descendants; everything provided can be reached by any component further down the tree. A component defines a provide function that returns the data or methods to share:
export default { provide() { return { sharedData: this.someData }; }, data() {
return { someData: 'This value is shared with child components' }; } };Inject
The inject option is declared in a descendant to use data or a method provided by an ancestor. With it, the provided value can be used directly in the child:
export default { inject: ['sharedData'], mounted() {
console.log(this.sharedData); // logs "This value is shared with child
components" } };Use cases and limits
provide and inject are useful in large component trees, when components are not directly parent and child. They are meant for specific cases, not as a replacement for global state management.
Provided values are not reactive by themselves: if you provide a plain value and it changes later, injecting components do not see the change. If you provide reactive data (for example an object created with Vue's reactive function, or a ref), its changes are reflected reactively.
Using provide and inject can make an application harder to follow, because you cannot tell from a template which ancestor a value comes from. Use them carefully and only when needed.
Have a question about this article? Write to me


