diff --git a/README.md b/README.md index 5f3cfba..0f6c861 100644 --- a/README.md +++ b/README.md @@ -401,6 +401,37 @@ app2.component('Bar', Bar) // equivalent to Vue.use('Bar', Bar) +### `createElement` / `h` + + +⚠️ createElement / h workaround + + +
+ +`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', + }) + }, +} +``` + + + + ### `shallowReadonly`
diff --git a/src/apis/createElement.ts b/src/apis/createElement.ts index c9c196a..7f8bc2d 100644 --- a/src/apis/createElement.ts +++ b/src/apis/createElement.ts @@ -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 @@ -20,7 +20,7 @@ export interface H extends CreateElement { children?: VNodeChildren ): VNode ( - this: ComponentInternalInstance | null, + this: ComponentInternalInstance | null | undefined, tag?: | string | Component @@ -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.') @@ -48,4 +48,4 @@ export const createElement = function createElement(this, ...args: any) { } return instance.$createElement.apply(instance, args) -} as H +}