• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • h()

    创建虚拟 DOM 节点(vnodes)。

    类型

    // full signature
    function h(
      type: string | Component,
      props?: object | null,
      children?: Children | Slot | Slots
    ): VNode
    
    // omitting props
    function h(type: string | Component, children?: Children | Slot): VNode
    
    type Children = string | number | boolean | VNode | null | Children[]
    
    type Slot = () => Children
    
    type Slots = { [name: string]: Slot }
    


    细节

    • type:第一个参数可以是字符串(用于原生元素)或 Vue 组件定义。
    • props:第二个参数是要传递的props
    • children:第三个参数。

    创建组件 vnode 时,子节点必须作为插槽函数传递。如果组件只需要默认槽,则可以传递单个槽函数。否则,槽必须作为槽函数的对象传递。

    为方便起见,当children不是 slot 对象时,可以省略props参数。


    例子

    创建原生元素

    import { h } from 'vue'
    
    // all arguments except the type are optional
    h('div')
    h('div', { id: 'foo' })
    
    // both attributes and properties can be used in props
    // Vue automatically picks the right way to assign it
    h('div', { class: 'bar', innerHTML: 'hello' })
    
    // class and style have the same object / array
    // value support like in templates
    h('div', { class: [foo, { bar }], style: { color: 'red' } })
    
    // event listeners should be passed as onXxx
    h('div', { onClick: () => {} })
    
    // children can be a string
    h('div', { id: 'foo' }, 'hello')
    
    // props can be omitted when there are no props
    h('div', 'hello')
    h('div', [h('span', 'hello')])
    
    // children array can contain mixed vnodes and strings
    h('div', ['hello', h('span', 'hello')])
    

    创建组件:

    import Foo from './Foo.vue'
    
    // passing props
    h(Foo, {
      // equivalent of some-prop="hello"
      someProp: 'hello',
      // equivalent of @update="() => {}"
      onUpdate: () => {}
    })
    
    // passing single default slot
    h(Foo, () => 'default slot')
    
    // passing named slots
    // notice the `null` is required to avoid
    // slots object being treated as props
    h(MyComponent, null, {
      default: () => 'default slot',
      foo: () => h('div', 'foo'),
      bar: () => [h('span', 'one'), h('span', 'two')]
    })
    

    下篇:mergeProps()