Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue3 inject() Function

Vue3 inject() Function


Vue3 Options API Vue3 Options API

inject() The function is an API provided by Vue 3, used in child components to obtain the dependencies provided by a parent or ancestor component via the provide() function. It is mainly used for data passing between cross-level components, especially when the component tree is deep.

Basic Syntax

Example

import

{

inject

}

from

'vue'

;

const

value

=

inject

(

key

,

defaultValue

)

;


Use Cases

inject() It is typically used together with the provide() used together, suitable for the following scenarios:

  1. Cross-Level Component Communication: When the component hierarchy is deep, using provide() and inject() can avoid the tedious process of passing props through each level.
  2. Global State Management: In small applications, you can use provide() and inject() instead of state management tools like Vuex.
  3. Plugin Development: When providing global functionality or configuration in a plugin,inject() is a convenient tool.

Code Example

Parent component uses provide() to supply data

Example

import

{

provide

,

ref

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

message

=

ref

(

'Hello, Vue3!'

)

;

    provide

(

'message'

,

message

)

;

// Provide data

 

}

}

;

Child component uses inject() to obtain data

Example

import

{

inject

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

message

=

inject

(

'message'

,

'Default Message'

)

;

// Inject data

   

return

{

message

}

;

 

}

}

;


Notes

  1. Reactivity of Dependencies: If the data provided via provide() is reactive (such as ref or reactive), the data obtained in the child component using inject() will also remain reactive.
  2. The Role of Default Values: If the corresponding dependency is not found,inject() returns the default value. It is recommended to always set a default value to avoid runtime errors.
  3. Avoid Overuse: Although provide() and inject() is convenient, overuse may increase coupling between components; it is recommended to use it only when necessary.

Vue3 Options API Vue3 Options API