Vue.js (original) (raw)

Composition API:

Dependency Injection

provide()

Provides a value that can be injected by descendant components.

function provide<T>(key: InjectionKey<T> | string, value: T): void  
<script setup>  
import { ref, provide } from 'vue'  
import { countSymbol } from './injectionSymbols'  
// provide static value  
provide('path', '/project/')  
// provide reactive value  
const count = ref(0)  
provide('count', count)  
// provide with Symbol keys  
provide(countSymbol, count)  
</script>  

inject()

Injects a value provided by an ancestor component or the application (via 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  
<script setup>  
import { inject } from 'vue'  
import { countSymbol } from './injectionSymbols'  
// inject static value without default  
const path = inject('path')  
// inject reactive value  
const count = inject('count')  
// inject with Symbol keys  
const count2 = inject(countSymbol)  
// inject with default value  
const bar = inject('path', '/default-path')  
// inject with function default value  
const fn = inject('function', () => {})  
// inject with default value factory  
const baz = inject('factory', () => new ExpensiveObject(), true)  
</script>  

hasInjectionContext()

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.

function hasInjectionContext(): boolean  

Edit this page on GitHub