【问题标题】:Are `h` and `createVNode` the same?`h` 和 `createVNode` 是一样的吗?
【发布时间】:2021-07-15 07:44:41
【问题描述】:

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 是从vue 暴露出来的,所以他们应该表现得一样吗?

标签: javascript vue.js vuejs3 virtual-dom vue-render-function


【解决方案1】:

对于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')

【讨论】:

    【解决方案2】:

    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
        )
    
    

    【讨论】:

      猜你喜欢
      • 2023-01-26
      • 2017-04-26
      • 2010-11-15
      • 2019-06-02
      • 2016-03-06
      • 2014-10-23
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多