Skip to content

Vue 中的 h 函数有什么用?

Posted on:2024年9月21日 at 01:58

1. h 函数概述

在 Vue 中,h 函数是一个用于创建虚拟 DOM 节点的工厂函数。它的全称是 createElement,在 Vue 3 中,它通常被直接引用为 h

2. 基本用法

h 函数的基本语法如下:

h(tag, props, children);

3. 创建虚拟 DOM 示例

下面是一个简单的使用 h 函数创建虚拟 DOM 的示例:

import { defineComponent, h } from "vue";

export default defineComponent({
  name: "MyComponent",
  render() {
    return h("div", { class: "my-class" }, [
      h("h1", "Hello World"),
      h("p", "This is a paragraph."),
    ]);
  },
});

在这个例子中,h 函数用于创建一个 div 元素,包含一个 h1 和一个 p 标签。返回的结果是一个虚拟 DOM 树。

4. 动态组件示例

使用 h 函数可以方便地创建动态组件。例如:

import { defineComponent, h, ref } from "vue";

const MyButton = { template: "<button>Button</button>" };
const MyLink = { template: '<a href="#">Link</a>' };

export default defineComponent({
  name: "DynamicComponent",
  setup() {
    const isButton = ref(true);

    return { isButton };
  },
  render() {
    const component = this.isButton ? MyButton : MyLink;
    return h(component);
  },
});

在这个例子中,根据 isButton 的值动态决定渲染哪个组件。

5. 与 JSX 结合

在 Vue 3 中,可以使用 JSX 来书写组件,h 函数在这里起到关键作用。示例如下:

/** @jsx h */
import { defineComponent } from "vue";

export default defineComponent({
  name: "MyComponent",
  render() {
    return (
      <div class="my-class">
        <h1>Hello World</h1>
        <p>This is a paragraph.</p>
      </div>
    );
  },
});

在 JSX 中,每个标签会被转换为 h 函数的调用。

6. 性能优化

h 函数通过创建虚拟 DOM,Vue 可以在数据变化时比较新旧虚拟 DOM,计算出最小的 DOM 更新,优化性能。这种方式避免了频繁的实际 DOM 操作,从而提升了应用的性能。

原文转自:https://fe.ecool.fun/topic/ead2f5e6-525a-4faf-956f-d97d90e933fe