當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Vue.js 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 }

為了便於閱讀,類型被簡化了。

細節

第一個參數可以是字符串(用於原生元素)或 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')]
})

相關用法


注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 h()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。