Skip to content

Commit

Permalink
feat(api): composition-api getCurrentInstance (vuejs#590)
Browse files Browse the repository at this point in the history
* feat(api): composition-api `getCurrentInstance`

* Update src/api/composition-api.md

Co-authored-by: Natalia Tepluhina <[email protected]>

Co-authored-by: Natalia Tepluhina <[email protected]>
  • Loading branch information
2 people authored and nick-lai committed Dec 2, 2020
1 parent 6e13af4 commit bdd5a77
Showing 1 changed file with 55 additions and 0 deletions.
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
}
```

0 comments on commit bdd5a77

Please sign in to comment.