Back to dictionary

Vue 3 Provide/Inject

Vue 3 Provide/Inject is a feature in Vue.js, a popular JavaScript framework, that allows for dependency injection. This feature is particularly useful when you want to pass data or methods from a parent component to a deeply nested child component without having to pass it through all the intermediate components.

In Vue 3, the 'provide' and 'inject' functions are part of the Composition API. The 'provide' function is used in a parent component to make certain properties available to its descendants. These properties can be data, computed properties, methods, or anything else that you want to make available to child components.

On the other hand, the 'inject' function is used in a child component to access the properties provided by its ancestor. It's important to note that 'inject' will traverse up the component tree until it finds the provided property. If it doesn't find the property, it will return 'undefined'.

Here's a simple example to illustrate this concept. Suppose you have a parent component that provides a user object:

import { provide } from 'vue'

export default {
  setup() {
    const user = { name: 'John Doe' }
    provide('user', user)
  }
}

In a deeply nested child component, you can inject the user object like this:

import { inject } from 'vue'

export default {
  setup() {
    const user = inject('user')
    return { user }
  }
}

In this example, the child component has direct access to the user object provided by the parent component, without having to pass it through all the intermediate components. This makes your code cleaner and easier to maintain.

However, it's worth noting that Vue 3 Provide/Inject should be used sparingly and only when necessary, as it can make your code harder to understand and debug. It's often better to use props and events for parent-child communication, as they make the data flow more explicit and easier to follow.