Vue 3 中 h 方法详解

在 Vue 3 中,h 方法是一个用于创建虚拟 DOM 节点的函数,它是创建渲染函数的核心工具。

一、引入 h 方法

import { h } from "vue";
const MyComponent = {
  render() {
    return h("div", "Hello, Vue 3!");
  },
};

二、语法

h(type, props?, children?)

1. type

必填参数,表示要创建的节点类型。

字符串:表示 HTML 标签名,如 'div''span''p' 等。
组件对象:可以是一个普通的 Vue 组件对象。
异步组件:使用 defineAsyncComponent 定义的异步组件。
函数式组件:一个返回虚拟 DOM 节点的函数。

2. props

可选参数,是一个对象,包含要传递给节点的属性、特性和事件监听器。

h("input", {
  type: "text",
  placeholder: "Enter your name",
  onInput: (event) => console.log(event.target.value),
});

3. children

可选参数,表示节点的子节点。

字符串:表示文本节点。
数组:数组中的每个元素可以是另一个 h 调用的结果,或者是字符串、数字等。
插槽对象:用于传递插槽内容。

三、示例

1. 创建简单的 HTML 元素

import { h } from "vue";
const MyComponent = {
  render() {
    // 创建一个 div 元素,包含文本内容
    return h("div", "This is a simple div");
  },
};

2. 创建带有属性的 HTML 元素

import { h } from "vue";
const MyComponent = {
  render() {
    // 创建一个带有属性的 a 元素
    return h(
      "a",
      {
        href: "https://www.example.com",
        target: "_blank",
      },
      "Visit Example.com"
    );
  },
};

3. 创建嵌套的 HTML 元素

import { h } from "vue";
const MyComponent = {
  render() {
    // 创建一个嵌套的结构:div 包含一个 p 元素
    return h("div", [h("p", "This is a paragraph inside a div")]);
  },
};

4. 创建自定义组件

import { h } from "vue";
// 定义一个自定义组件
const MyCustomComponent = {
  props: ["message"],
  render() {
    return h("p", this.message);
  },
};
const ParentComponent = {
  render() {
    // 使用 h 方法创建自定义组件实例
    return h(MyCustomComponent, { message: "Hello from custom component" });
  },
};

你可能感兴趣的:(前端,javascript,开发语言)