Skip to content

Commit

Permalink
docs: note about createElement workaround
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Apr 25, 2022
1 parent e0128e3 commit 7c1c248
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
31 changes: 31 additions & 0 deletions README.md
Expand Up @@ -401,6 +401,37 @@ app2.component('Bar', Bar) // equivalent to Vue.use('Bar', Bar)

</details>

### `createElement` / `h`

<summary>
⚠️ <code>createElement</code> / <code>h</code> workaround
</summary>

<br>

`createElement` / `h` in Vue 2 is only accessable in `render()` function. To use it outside of `render()`, you can explicitly bind a component instance to it.

> :warning: **Warning**: This ability is provided as a workaround Vue 2, it's not part of the Vue 3 API.
```jsx
import { h as _h } from '@vue/composition-api'

export default {
setup() {
const vm = getCurrentInstance()
const h = _h.bind(vm)

return () =>
h('div', {
ref: 'root',
})
},
}
```

</details>


### `shallowReadonly`

<details>
Expand Down
10 changes: 5 additions & 5 deletions src/apis/createElement.ts
Expand Up @@ -11,7 +11,7 @@ import { VNode, VNodeChildren, VNodeData } from 'vue/types/vnode'

export interface H extends CreateElement {
(
this: ComponentInternalInstance | null,
this: ComponentInternalInstance | null | undefined,
tag?:
| string
| Component<any, any, any, any>
Expand All @@ -20,7 +20,7 @@ export interface H extends CreateElement {
children?: VNodeChildren
): VNode
(
this: ComponentInternalInstance | null,
this: ComponentInternalInstance | null | undefined,
tag?:
| string
| Component<any, any, any, any>
Expand All @@ -33,8 +33,8 @@ export interface H extends CreateElement {

let fallbackCreateElement: CreateElement

export const createElement = function createElement(this, ...args: any) {
const instance = this ? this.proxy : getCurrentInstance()?.proxy
export const createElement: H = function createElement(this, ...args: any) {
const instance = this?.proxy || getCurrentInstance()?.proxy
if (!instance) {
__DEV__ &&
warn('`createElement()` has been called outside of render function.')
Expand All @@ -48,4 +48,4 @@ export const createElement = function createElement(this, ...args: any) {
}

return instance.$createElement.apply(instance, args)
} as H
}

0 comments on commit 7c1c248

Please sign in to comment.