h and Render Functions

When using the render function instead of templates, you'll be using the h function a lot:

<script setup>
import { h } from 'vue';
const render = () => h('div', {}, 'Hello Wurld');
</script>

With the Options API the render function works exactly the same, we just have to define it slightly differently:

<script>
import { h } from 'vue';
export default {
render() {
return h('div', {}, 'Hello Wurld');
}
}
</script>

It creates a VNode (virtual node), an object that Vue uses internally to track updates and what it should be rendering.

The first argument is either an HTML element name or a component (which can be async if you want):

<script setup>
import { h } from 'vue';
import MyComponent from './MyComponent.vue';
const render = () => h(MyComponent, {}, []);
</script>

The second argument is a list of props, attributes, and event handlers:

<script setup>
import { h } from 'vue';
import MyComponent from './MyComponent.vue';
const render = () => h(MyComponent, {
class: 'text-blue-400',
title: 'This component is the greatest',
onClick() {
console.log('Clicked!');
},
}, []);
</script>

The third argument is either a string for a text node, an array of children VNodes, or an object for defining slots:

<script setup>
import { h } from 'vue';
import MyComponent from './MyComponent.vue';
const render = () => h(MyComponent, {}, [
'Simple text node',
h('span', {}, 'Text inside of a <span> element'),
]);
</script>

These render functions are essentially what is happening "under the hood" when Vue compiles your single file components to be run in the browser.

But by writing out the render function yourself, you are no longer constrained by what can be done in a template.

You have the full power of Javascript at your fingertips 🖐

This is just scratching the surface on what render functions and h can do. Read more about them on the official docs.