注入由祖先組件或應用程序提供的值(通過 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
細節
第一個參數是注入 key 。 Vue 將沿著父鏈查找具有匹配鍵的提供值。如果父鏈中的多個組件提供相同的 key ,則最接近注入組件的一個將"shadow" 那些更高的鏈。如果未找到具有匹配鍵的值,則 inject()
將返回 undefined
,除非提供了默認值。
第二個參數是可選的,是在沒有找到匹配值時使用的默認值。它也可以是一個工廠函數來返回創建成本高的值。如果默認值是一個函數,那麽false
必須作為第三個參數傳遞,以指示該函數應該用作值而不是工廠。
與生命周期鉤子注冊 API 類似,inject()
必須在組件的 setup()
階段同步調用。
使用 TypeScript 時,鍵的類型可以是 InjectionKey
- 擴展 Symbol
的 Vue-provided 實用程序類型,可用於在 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>
相關用法
- Vue.js inject用法及代碼示例
- Vue.js inheritAttrs用法及代碼示例
- Vue.js useSSRContext()用法及代碼示例
- Vue.js app.directive()用法及代碼示例
- Vue.js mergeProps()用法及代碼示例
- Vue.js app.config.warnHandler用法及代碼示例
- Vue.js pipeToWebWritable()用法及代碼示例
- Vue.js app.use()用法及代碼示例
- Vue.js v-pre用法及代碼示例
- Vue.js h()用法及代碼示例
- Vue.js serverPrefetch用法及代碼示例
- Vue.js customRef()用法及代碼示例
- Vue.js <Transition>用法及代碼示例
- Vue.js mixins用法及代碼示例
- Vue.js ComponentCustomProps用法及代碼示例
- Vue.js reactive()用法及代碼示例
- Vue.js ComponentCustomProperties用法及代碼示例
- Vue.js app.mount()用法及代碼示例
- Vue.js <component>用法及代碼示例
- Vue.js createRenderer()用法及代碼示例
- Vue.js onMounted()用法及代碼示例
- Vue.js createApp()用法及代碼示例
- Vue.js app.config.errorHandler用法及代碼示例
- Vue.js v-on用法及代碼示例
- Vue.js components用法及代碼示例
注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 inject()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。