vue3 [The function and usage of the h function - setup syntax sugar]

1. Introduction

  • What vue internally builds is actually a virtual DOM, and the virtual DOM is generated by a virtual node. In essence, a virtual node is a js object
  • In fact, the template we wrote in vue eventually generates the corresponding VNode through the rendering function

  • The h function is a function used to generate VNode, its full name is createVNode

 2. Parameter explanation

  • The first parameter: the tag name of the node, which is a string, which must be passed. This string can be an HTML tag name, a component, an asynchronous component or a function component
  • The second parameter: the attribute of the node, added by object, such as class, style, etc., optional
  • The third parameter: the content in the node label, which can be a string, an array or an object, it is VNodes, use the h function to create
// @returns {VNode}
h(
  // {String | Object | Function | null} tag
  // 一个 HTML 标签名、一个组件、一个异步组件,或者 null。
  // 使用 null 将会渲染一个注释。
  //
  // 必需的。
  'div',

  // {Object} props
  // 与 attribute、prop 和事件相对应的对象。
  // 我们会在模板中使用。
  //
  // 可选的。
  {},

  // {String | Array | Object} children
  // 子 VNodes, 使用 `h()` 构建,
  // 或使用字符串获取 "文本 Vnode" 或者
  // 有插槽的对象。
  //
  // 可选的。
  [
    'Some text comes first.',
    h('h1', 'A headline'),
    h(MyComponent, {
      someProp: 'foobar'
    })
  ]
)

3. Actual use

<template>
    <div class='main'>
        <render></render>
    </div>

</template>

<script setup>
import { ref, onMounted, h } from 'vue'

// render一个标签
const conter = ref(0)
const increment = () => {
    conter.value++
}
const decrement = () => {
    conter.value--
}
// 将这个render函数保存到一个变量中
const render = () => h("div", { class: "app" }, [
    h("h2", { class: "title" }, `当前计数: ${conter.value}`),
    h("button", { onclick: increment }, "+"),
    h("button", { onclick: decrement }, "-")
])

onMounted(() => {
    // 获取子组件的名称和方法
})

</script>
<style scoped lang='less'>
.main {
    width: 500px;
    height: 500px;
    background: #1cd66c;
    margin: 0 auto;
}
</style>

Guess you like

Origin blog.csdn.net/qq_41579104/article/details/130768711