Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api): composition-api getCurrentInstance #590

Merged
merged 2 commits into from
Oct 4, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/api/composition-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,58 @@ const foo = inject<string>('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
}
```