`h` 和 `createVNode` 相同吗?

问题描述

hcreateVNode 都从 vue 公开。

doc 似乎表明它们是相同的:

h() 函数一个创建 VNode 的实用程序。或许可以更准确地将其命名为 createVNode()

但是将 h 切换到 createVNode 会抛出:

<script lang="ts">
  import { createVNode,defineComponent,h } from 'vue'

  export default defineComponent({
    setup() {
      // works
      return () => h('strong','Foo')

      // throws
      return () => createVNode('strong','Foo')
    },})
</script>

解决方法

createVNode 已公开,但 h 是它的用户友好变体。如果您想直接调用 createVNode,您应该添加不同类型的参数,请参阅:

https://github.com/vuejs/vue-next/blob/060c5f1d0ae999cd8c8fb965e8526ffab17ac2d1/packages/runtime-core/src/vnode.ts#L326


    export const createVNode = (__DEV__
      ? createVNodeWithArgsTransform
      : _createVNode) as typeof _createVNode

    function _createVNode(
      type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT,props: (Data & VNodeProps) | null = null,children: unknown = null,patchFlag: number = 0,dynamicProps: string[] | null = null,isBlockNode = false
    )

,

对于h

If there are no props then the children can usually be passed as the second argument.

你可以这样做:

h('strong','Foo')

对于createVNode,您必须:

createVNode('strong',null,'Foo')