From 7c1c248004e63e9f7d3b1fe6c77446f08bd01d01 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Mon, 25 Apr 2022 12:49:13 +0800 Subject: [PATCH] docs: note about `createElement` workaround --- README.md | 31 +++++++++++++++++++++++++++++++ src/apis/createElement.ts | 10 +++++----- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5f3cfba7..0f6c8616 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 c9c196aa..7f8bc2d6 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 +}