Vue3 inject() Function
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
)
;
- key: A string or Symbol representing the unique identifier of the dependency to be injected.
- defaultValue: An optional parameter; if the corresponding dependency is not found, the default value is returned.
Use Cases
inject() It is typically used together with the provide() used together, suitable for the following scenarios:
- Cross-Level Component Communication: When the component hierarchy is deep, using
provide()andinject()can avoid the tedious process of passing props through each level. - Global State Management: In small applications, you can use
provide()andinject()instead of state management tools like Vuex. - 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
- Reactivity of Dependencies: If the data provided via
provide()is reactive (such asreforreactive), the data obtained in the child component usinginject()will also remain reactive. - 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. - Avoid Overuse: Although
provide()andinject()is convenient, overuse may increase coupling between components; it is recommended to use it only when necessary.
Vue3 Options API