SoFunction
Updated on 2025-04-05

The use of vue multi-function rendering function h and various application scenarios

Preface

according tovueOfficial introduction,h()Rendering functions are used to create virtualDOMnodevnode. We're invueUsed in the projectHTMLTags will eventually be converted intovnode,andh()It is created directlyvnode,thereforeh()The rendering logic of components can be built in a wide variety of scenarios in a more flexible way, and can bring about improvements in performance. The following describes how to use and list specific application scenarios:

1. The use of h() rendering function syntax

As shown below, there are three main parameters, among which the second and third parameters are optional

  • type: The node type to be created can be an HTML tag, component, or function (functional component).
  • Props (optional): The attribute object of the node, the prop passed.
  • children (optional): The child node of a node, which can be a string, an array, or other vnode.
// Syntax formatfunction h(
  type: string | Component,
  props?: object | null,
  children?: Children | Slot | Slots
): VNode

// Basic usage exampleh('div', { id: 'foo' }, 'Hello I'm Tiantian duck!');

Detailed explanation of the parameters of the h function

(1) Type parameters:

  • HTML tag: If type is a string, it will be recognized and parsed into an HTML tag.
  • Component: If type is an object or function, it will be parsed into a Vue component.
  • Asynchronous component: type can also be a function that returns a Promise, and the Promise will be parsed into a component.

(2) props parameters:

  • props are optional parameters that specify the attribute parameters of the node. If props are passed, the side should pass an object containing the attribute name and value passed to the node.
  • If props are passed, null can be passed.

(3) Children parameters:

  • children is an optional parameter that specifies the child node of the current node. Children can be strings, arrays, or vnode objects.
  • If the child node is an array, each element in the array is a child of that node.
  • If a child node is a function, the function will be called during rendering and its return value will be used as a child node.

2. Specific application examples

Just looking at the syntax may not be easy to understand when you should use ith()The following lists several suitable functions in real projectsh()business scenarios.

(1) Dynamic rendering component

As shown below, combinedcomponentImplementing dynamic components is one of the most commonly used business scenarios, but many people don't know how to use them in this situation.h()Implement some functions. In fact, it is usefulh()It can avoid the overhead of template compilation, and in this scenario, it can bring performance optimization and be more flexible in processing.

<template>
  <button @click="changeComponent">Switch dynamic components</button>
  <component :is="createComponent()" />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import ComponentA from './';
import ComponentB from './';

const nowComponent = ref('ComponentA');

function changeComponent() {
   =  === 'ComponentA' ? 'ComponentB' : 'ComponentA';
}

const createComponent = () => {
  return h( === 'ComponentA' ? ComponentA : ComponentB);
};
</script>

(2) Create functional components

useh()Creating functional components can be independently removed and maintained without creating an additional one.vueThe file is really not too practical. This method is very suitable for simpleUIComponents that can significantly simplify code and improve performance.

<template>
  <FunctionalComponent text="This is a functional component" @click="handleClick" />
</template>

<script setup lang="ts">
import { h, defineEmits } from 'vue';

const FunctionalComponent = (props, context) => {
  return h('div', null, [
    h('p', null, ),
    h('button', { onClick: (context, 'click') }, 'Click me')
  ]);
};

const emit = defineEmits(['click']);

function handleClick() {
  ('handleClick');
}
</script>

As shown above, it is a typical way to use functional components, which includes how to interact with them in parent-child components. Functional ComponentsFunctionalComponenttake overpropsandcontextParameters and useh()Functions to build the page. Passed again at the same timeMethod to trigger event handler in parent component.

Notice:propsUsed to receive attributes passed by the parent component.contextUsed to access component contexts such as slots slots and method events.

(3) Render dynamic properties

If a component or a tag needs to define some dynamic properties, then useh()Rendering functions are quite convenient

<template>
  <button @click="myVisibility">Switch component display status</button>
  <component :is="componentWithProps()" />
</template>

<script setup lang="ts">
  import { ref } from 'vue';

  const visible = ref(true);

  function myVisibility() {
     = !;
  }

  const componentWithProps = () => {
    return h('div', { class: { visible:  } }, 'I am a div');
  };
</script>

As shown above,h()The function is based onvisibleThe value ofvnodeWhether or notvisibleThis class implements dynamic styles when a button is clicked. Of course, dynamic classes are just an example.h()All the properties or subcomponents inside can be dynamic, and their flexibility is far beyond the use.HTMLaccomplish.

(4) Use slots

h()If functional components and slots are combined to deliver content, it can improve flexibility when using it.

<template>
  <SlotComponent>
    <template #default>
      <p>I'm inside the slot</p>
    </template>
  </SlotComponent>
</template>

<script setup lang="ts">
import { h } from 'vue';

const SlotComponent = (props, context) => {
  return h('div', null, [
    h('p', null, 'Inside the slot:'),
     && ()
  ]);
};
</script>

As shown above, quoteSlotComponentWhen the component is internal<template>The content in the tag will be passed to the content of the default slot as the content of theSlotComponentComponents. And can pass()To get and render the content in the default slot. Therefore, when we encapsulate a functional component but there is a certain part of it dynamic, it is particularly suitable for flexibly using the slot.

Notice:propsUsed to receive attributes passed by the parent component.contextUsed to access component contexts such as slots slots and method events.

(5) Create dynamic tags

The following code ish()Functions combined with dynamic components to implement in differentHTMLSwitch between labels.

&lt;template&gt;
  &lt;button @click="changeTag"&gt;Switch tags&lt;/button&gt;
  &lt;component :is="createElement()" /&gt;
&lt;/template&gt;

&lt;script setup lang="ts"&gt;
import { ref } from 'vue';

const tag = ref('div');

function changeTag() {
   =  === 'div' ? 'section' : 'div';
}

const createElement = () =&gt; {
  return h(, null, 'Dynamic Tag');
};
&lt;/script&gt;

As shown above, it is actually based ontagThe value of the decision to returnHTMLTagsVNode,It is very easy to use if the business logic involves dynamic changes in labels, avoid using itv-ifGenerates a lot of duplicate code.

summary

After summarizing it up, you will find thath()Rendering functions are applicable to many application scenarios and are quite flexible in usage, absolutelyPanaceafunction. The above are several practical scenarios I have summarized. If you have any wrong writing or if you have better suggestions, please give me some advice.

The above is the detailed content of the use of vue multi-function rendering function h() and various application scenarios. For more information about the usage of vue rendering function h(), please pay attention to my other related articles!