diff --git a/src/api/composition-api.md b/src/api/composition-api.md index 2494474fe8..f6c9e6ba0b 100644 --- a/src/api/composition-api.md +++ b/src/api/composition-api.md @@ -158,3 +158,58 @@ const foo = inject('foo') // string | undefined - **See also**: - [Provide / Inject](../guide/component-provide-inject.html) - [Composition API Provide / Inject](../guide/composition-api-provide-inject.html) + +## `getCurrentInstance` + +`getCurrentInstance` enables access to an internal component instance useful for advanced usages or for library creators. + +```ts +import { getCurrentIntance } from 'vue' + +const MyComponent = { + setup() { + const internalIntance = getCurrentInstance() + + internalInstance.appContext.config.globalProperties // access to globalProperties + } +} +``` + +`getCurrentInstance` **only** works during [setup](#setup) or [Lifecycle Hooks](#lifecycle-hooks) + +> When using outside of [setup](#setup) or [Lifecycle Hooks](#lifecycle-hooks), please call `getCurrentInstance()` on `setup` and use the instance instead. + +```ts +const MyComponent = { + setup() { + const internalIntance = getCurrentInstance() // works + + const id = useComponentId() // works + + const handleClick = () => { + getCurrentInstance() // doesn't work + useComponentId() // doesn't work + + internalIntance // works + } + + onMounted(() => { + getCurrentInstance() // works + }) + + return () => + h( + 'button', + { + onClick: handleClick + }, + `uid: ${id}` + ) + } +} + +// also works if called on a composable +function useComponentId() { + return getCurrentInstance().uid +} +```