inject()
注入由祖先组件或应用程序提供的值(通过app.provide()
)。
类型
// without default value function inject<T>(key: InjectionKey<T> | string): T | undefined // with default value function inject<T>(key: InjectionKey<T> | string, defaultValue: T): T // with factory function inject<T>( key: InjectionKey<T> | string, defaultValue: () => T, treatDefaultAsFactory: true ): T
细节
第一个参数是注入密钥。Vue 将沿着父链查找具有匹配键的提供值。如果父链中的多个组件提供相同的密钥,则最接近注入组件的一个将“遮蔽”链上更高的那些。如果没有找到具有匹配键的值,则inject()
返回
第二个参数是可选的,是在没有找到匹配值时使用的默认值。它也可以是一个工厂函数来返回创建成本高的值。如果默认值是一个函数,则
与生命周期挂钩注册 API 类似,inject()
必须在组件setup()
阶段同步调用。
使用 TypeScript 时,键的类型可以是InjectionKey
。Vue 提供的扩展实用程序类型,Symbol()
可用于在provide()
和之间同步值类型inject()
。
例子
假设父组件已提供如上provide()
例所示的值:
<script setup> import { inject } from 'vue' import { fooSymbol } from './injectionSymbols' // inject static value with default const foo = inject('foo') // inject reactive value const count = inject('count') // inject with Symbol keys const foo2 = inject(fooSymbol) // inject with default value const bar = inject('foo', 'default value') // inject with default value factory const baz = inject('foo', () => new Map()) // inject with function default value, by passing the 3rd argument const fn = inject('function', () => {}, false) </script>