Skip to content

渲染函数 & JSX

我是自定义的组件 default slot
我是自定义的组件 default slot
header slot
我是自定义的组件 default slot
footer slot

Markdown Content

The count is: 0

h()

ts
// 完整参数签名
function h(
  type: string | Component,
  props?: object | null,
  children?: Children | Slot | Slots
): VNode;

第一个参数既可以是一个字符串 (用于原生元素) 也可以是一个 Vue 组件定义。第二个参数是要传递的 prop,第三个参数是子节点。

当创建一个组件的 vnode 时,子节点必须以插槽函数进行传递。如果组件只有默认槽,可以使用单个插槽函数进行传递。否则,必须以插槽函数的对象形式来传递。

为了方便阅读,当子节点不是插槽对象时,可以省略 prop 参数。

创建元素:

javascript
const renderDiv = () =>
  h("div", { class: "test" }, [h("h1", "hello world"), h("p", "hello world")]);

// 创建一个img元素
const renderImg = () =>
  h("img", {
    src: "https://www.baidu.com/img/flexible/logo/pc/result.png",
    alt: "百度logo",
    width: 100,
    height: 100,
  });
hello world

hi

hi

hi

hi

hello world

百度logo

创建组件:

javascript
import MyComponent from "./components/MyComponent.vue";

const renderComponent = () =>
  h(MyComponent, { class: "test" }, [
    h("h1", "hello world"),
    h("p", "hello world"),
  ]);

function renderComponent2() {
  return h(MyComponent);
}
我是自定义的组件
我是自定义的组件

插槽函数:

js
// 默认插槽
const renderSlot1 = h(MyComponent, () => "default slot");
const renderSlot2 = h(
  MyComponent,
  { class: "test" },
  { default: () => "default slot" }
);
// 具名插槽
const renderSlot3 = h(
  MyComponent,
  { class: "test" },
  {
    default: () => "default slot",
    header: () => "header slot",
    footer: () => "footer slot",
  }
);
我是自定义的组件 default slot
我是自定义的组件 default slot
header slot
我是自定义的组件 default slot
footer slot

遍历渲染

Released Under The MIT License.