Sobes.tech
Middle

How does provide/inject work in Vue 3?

sobes.tech AI

Answer from AI

In Vue 3, provide/inject is used to pass data or dependencies from a parent component to its descendants, bypassing intermediate components.

  • provide is declared in the parent component and supplies values.
  • inject is used in child components to access these values.

This is convenient for passing global settings, services, or data needed by deeply nested components without having to pass props through every level.

Example:

// Parent component
export default {
  setup() {
    provide('theme', 'dark')
  }
}

// Child component
export default {
  setup() {
    const theme = inject('theme')
    return { theme }
  }
}

Thus, the child component gains access to the 'dark' value provided by the parent.