創建虛擬 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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。