0
0
Vueframework~5 mins

h function for creating vnodes in Vue

Choose your learning style9 modes available
Introduction

The h function helps you create virtual nodes (vnodes) which represent HTML elements or components in Vue. It lets Vue know what to show on the screen.

When you want to create elements inside a render function instead of a template.
When you need to build components dynamically with JavaScript.
When you want full control over the structure of your component output.
When you are writing a library or plugin that generates Vue elements programmatically.
Syntax
Vue
h(tag, props?, children?)

tag can be a string like 'div' or a component object.

props is an optional object for attributes, events, or props.

Examples
Creates a simple <div> element with no props or children.
Vue
h('div')
Creates a button with a click event and text inside.
Vue
h('button', { onClick: () => alert('Clicked!') }, 'Click me')
Creates a custom component with a prop called someProp.
Vue
h(MyComponent, { someProp: 123 })
Creates a list with two items as children.
Vue
h('ul', null, [h('li', null, 'Item 1'), h('li', null, 'Item 2')])
Sample Program

This Vue component uses the h function to create a button. When clicked, it shows an alert. The button has some simple inline styles.

Vue
import { h, defineComponent } from 'vue';

export default defineComponent({
  name: 'HelloButton',
  setup() {
    const handleClick = () => alert('Hello from h!');
    return () => h('button', { onClick: handleClick, style: { padding: '0.5rem', fontSize: '1rem' } }, 'Say Hello');
  }
});
OutputSuccess
Important Notes

The h function is the core way Vue builds its virtual DOM.

Using h gives you flexibility but templates are easier for simple cases.

Remember to use camelCase for event names in props, like onClick.

Summary

The h function creates virtual nodes representing elements or components.

It takes a tag, optional props, and optional children.

Use it inside render functions for dynamic or programmatic UI creation.