Vue Provide / Inject

Vue Provide / Inject

Usually, when you need to pass data from a parent to a child component, you use props.

However, what happens if the child is deeply nested 5 levels down?

You would have to pass the prop through every single intermediate component, which is called "prop drilling".


Solving Prop Drilling

Prop drilling creates messy code, because intermediate components are forced to declare props they don't even use.

Vue solves this massive headache with the provide and inject system.

A parent component can serve as a dependency provider for all its descendants, no matter how deep they are!


The Provide Method

To provide data, you add a provide option to the top-level parent component.

You simply return an object containing the keys and values you want to share.

Provide Example:

export default {
  provide() {
    return {
      message: 'Hello from the top level Parent!'
    }
  }
}

This message is now floating in a magical bubble, accessible by any descendant component.


The Inject Method

To grab this data inside a deeply nested child, you use the inject option.

You simply declare an array of the keys you want to grab from the provider.

Once injected, they act exactly like normal props or local data variables!

Inject Example:

export default {
  // Grabs 'message' from the ancestor provider
  inject: ['message'],
  created() {
    console.log(this.message) // Outputs: Hello from the top level Parent!
  }
}

Reactivity in Provide/Inject

By default, provide and inject bindings are NOT reactive.

If the parent's data changes, the injected value in the child will not update automatically.

If you need reactivity, you must provide a computed property or a reactive ref() variable instead of a plain string.


Exercise 1 of 2

?

What specific structural problem does Provide/Inject solve?

Exercise 2 of 2

?

Are provided values automatically reactive by default?