网页
综合
更新时间 2026-11-13 16:58:56
Composition API: Dependency Injection | Vue.js
自动蜘蛛
vuejs.org
正文约 2145 字
Reactivity: Utilities
Reactivity: Advanced
Dependency Injection
Options: Composition
Syntax Specification
Server-Side Rendering
TypeScript Utility Types
Provides a value that can be injected by descendant components.
provide() takes two arguments: the key, which can be a string or a symbol, and the value to be injected.
When using TypeScript, the key can be a symbol casted as InjectionKey - a Vue provided utility type that extends Symbol, which can be used to sync the value type between provide() and inject().
Similar to lifecycle hook registration APIs, provide() must be called synchronously during a component's setup() phase.
Injects a value provided by an ancestor component or the application (via app.provide()).
The first argument is the injection key. Vue will walk up the parent chain to locate a provided value with a matching key. If multiple components in the parent chain provide the same key, the one closest to the injecting component will "shadow" those higher up the chain and its value will be used. If no value with matching key was found, inject() returns undefined unless a default value is provided.
The second argument is optional and is the default value to be used when no matching value was found.
The second argument can also be a factory function that returns values that are expensive to create. In this case, true must be passed as the third argument to indicate that the function should be used as a factory instead of the value itself.
Similar to lifecycle hook registration APIs, inject() must be called synchronously during a component's setup() phase.
When using TypeScript, the key can be of type of InjectionKey - a Vue-provided utility type that extends Symbol, which can be used to sync the value type between provide() and inject().
Assuming a parent component has provided values as shown in the previous provide() example:
Returns true if inject() can be used without warning about being called in the wrong place (e.g. outside of setup()). This method is designed to be used by libraries that want to use inject() internally without triggering a warning to the end user.
Edit this page on GitHub
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。