创建虚拟 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 }
为了便于阅读,类型被简化了。
细节
第一个参数可以是字符串(用于原生元素)或 Vue 组件定义。第二个参数是要传递的道具,第三个参数是孩子。
创建组件 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')]
})
相关用法
- Vue.js useSSRContext()用法及代码示例
- Vue.js app.directive()用法及代码示例
- Vue.js mergeProps()用法及代码示例
- Vue.js app.config.warnHandler用法及代码示例
- Vue.js pipeToWebWritable()用法及代码示例
- Vue.js app.use()用法及代码示例
- Vue.js v-pre用法及代码示例
- Vue.js serverPrefetch用法及代码示例
- Vue.js customRef()用法及代码示例
- Vue.js <Transition>用法及代码示例
- Vue.js inject()用法及代码示例
- Vue.js mixins用法及代码示例
- Vue.js ComponentCustomProps用法及代码示例
- Vue.js reactive()用法及代码示例
- Vue.js ComponentCustomProperties用法及代码示例
- Vue.js app.mount()用法及代码示例
- Vue.js <component>用法及代码示例
- Vue.js createRenderer()用法及代码示例
- Vue.js onMounted()用法及代码示例
- Vue.js createApp()用法及代码示例
- Vue.js app.config.errorHandler用法及代码示例
- Vue.js v-on用法及代码示例
- Vue.js components用法及代码示例
- Vue.js app.compilerOptions.isCustomElement用法及代码示例
- Vue.js $emit()用法及代码示例
注:本文由纯净天空筛选整理自vuejs.org大神的英文原创作品 h()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。