Skip to content

Commit 2865878

Browse files
feat(api): composition-api getCurrentInstance (#590)
* 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]>
1 parent b6070fe commit 2865878

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/api/composition-api.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,58 @@ const foo = inject<string>('foo') // string | undefined
158158
- **See also**:
159159
- [Provide / Inject](../guide/component-provide-inject.html)
160160
- [Composition API Provide / Inject](../guide/composition-api-provide-inject.html)
161+
162+
## `getCurrentInstance`
163+
164+
`getCurrentInstance` enables access to an internal component instance useful for advanced usages or for library creators.
165+
166+
```ts
167+
import { getCurrentIntance } from 'vue'
168+
169+
const MyComponent = {
170+
setup() {
171+
const internalIntance = getCurrentInstance()
172+
173+
internalInstance.appContext.config.globalProperties // access to globalProperties
174+
}
175+
}
176+
```
177+
178+
`getCurrentInstance` **only** works during [setup](#setup) or [Lifecycle Hooks](#lifecycle-hooks)
179+
180+
> When using outside of [setup](#setup) or [Lifecycle Hooks](#lifecycle-hooks), please call `getCurrentInstance()` on `setup` and use the instance instead.
181+
182+
```ts
183+
const MyComponent = {
184+
setup() {
185+
const internalIntance = getCurrentInstance() // works
186+
187+
const id = useComponentId() // works
188+
189+
const handleClick = () => {
190+
getCurrentInstance() // doesn't work
191+
useComponentId() // doesn't work
192+
193+
internalIntance // works
194+
}
195+
196+
onMounted(() => {
197+
getCurrentInstance() // works
198+
})
199+
200+
return () =>
201+
h(
202+
'button',
203+
{
204+
onClick: handleClick
205+
},
206+
`uid: ${id}`
207+
)
208+
}
209+
}
210+
211+
// also works if called on a composable
212+
function useComponentId() {
213+
return getCurrentInstance().uid
214+
}
215+
```

0 commit comments

Comments
 (0)