Since the very first lesson, every interface in Colmena Bookings has been described with templates, and Vue's compiler has turned them into JavaScript code without you ever having to see it. That generated code is a render function: a function that returns a description of the DOM in the form of objects, virtual nodes (VNodes). Vue lets you write those functions by hand, with h() or with JSX, and for some components it is the most natural way: those that decide their structure with programming logic (which tag to use, how many columns to render, which slot belongs to each cell), those that need no state, and library components that must be very flexible. In this lesson you will see what the compiler produces and what a VNode is, all the forms of h(), how each template directive translates into code, functional components, when it pays off (and when it does not) to abandon templates, and JSX with @vitejs/plugin-vue-jsx. In Colmena you will rewrite SectionTitle as a render function, create a DataTable configurable by columns for the invoices and a functional EquipmentIcon component.
As we announced in 09-02, the code in this lesson and the following ones is in JavaScript; everything works the same in TypeScript (render functions and JSX are typed like any other function, and typed JSX files use the
.tsxextension).
Contents
- From the template compiler to VNodes
h(): creating virtual nodes- Returning a render function from
setup - Equivalences between templates and render functions
- Functional components
- When to use render functions and when not to
- Colmena:
SectionTitleas a render function - Colmena:
DataTable, a table configurable by columns - Colmena:
EquipmentIcon, a functional component - JSX with
@vitejs/plugin-vue-jsx - Try it
- From the template compiler to VNodes
In Template Syntax you saw, in simplified form, the function the compiler generates from a template. Let's now look at the real output for a fragment similar to RoomCard:
<article class="card">
<h3>{{ room.name }}</h3>
<p class="card__note">Price per hour</p>
<button :disabled="full" @click="book">Book</button>
</article>Vue's compiler produces (you can see it for yourself in the Vue SFC Playground, in the JS tab):
import { toDisplayString as _toDisplayString, createElementVNode as _createElementVNode,
openBlock as _openBlock, createElementBlock as _createElementBlock } from 'vue'
const _hoisted_1 = { class: 'card' }
const _hoisted_2 = ['disabled', 'onClick']
export function render(_ctx, _cache) {
return (_openBlock(), _createElementBlock('article', _hoisted_1, [
_createElementVNode('h3', null, _toDisplayString(_ctx.room.name), 1 /* TEXT */),
_cache[0] || (_cache[0] = _createElementVNode('p', { class: 'card__note' }, 'Price per hour', -1 /* CACHED */)),
_createElementVNode('button', {
disabled: _ctx.full,
onClick: _ctx.book
}, 'Book', 8 /* PROPS */, _hoisted_2)
]))
}Each call to _createElementVNode returns a VNode: a JavaScript object that describes an element (its type, its attributes, its children). The whole set is called the virtual DOM. When the state changes, Vue runs the function again, gets a new tree, compares it with the previous one and applies only the differences to the real DOM.
But notice the extra information the compiler has added, because it will matter in section 6:
_hoisted_1: the{ class: 'card' }object is created only once, outside the function, because it never changes._cache[0]: the static paragraph is created the first time and reused on every render (-1 /* CACHED */). Vue does not even compare it.1 /* TEXT */and8 /* PROPS */are patch flags: they tell Vue that only the text of the<h3>can change, and only thedisabledandonClickprops of the button (those in_hoisted_2). When comparing, it looks only at those.openBlock/createElementBlockform a block: the root node keeps a list of its dynamic descendants, and when updating, Vue walks through that list instead of the whole tree.
A VNode has this shape (simplified):
{
type: 'button', // HTML tag, a component or a special symbol (Fragment, Text...)
props: { disabled: false, onClick: fn },
children: 'Book', // text, an array of VNodes or a slots object
key: null, // the :key, if there is one
el: null, // the real DOM element, once mounted
patchFlag: 8, // compiler hints (they do not exist when you write h() by hand)
// ...
}Writing a render function by hand means writing yourself what the compiler does, with one key difference: without the optimisation hints.
h(): creating virtual nodes
h(): creating virtual nodesThe public function for creating VNodes is h() (from hyperscript, "script that generates HTML"). Its signature is h(type, props, children), with several shorthand forms:
| Form | Example | Result |
|---|---|---|
| Type only | h('hr') |
<hr> |
| Type and text | h('h3', 'Panal Room') |
<h3>Panal Room</h3> |
| Type and an array of children | h('ul', [h('li', 'One'), h('li', 'Two')]) |
A list with two items |
| Type and props | h('img', { src: '/img/rooms/panal.webp', alt: 'Panal Room' }) |
An image with attributes |
| Type, props and children | h('button', { class: 'button', onClick: book }, 'Book') |
A button with a class and an event |
| A component | h(StatusBadge, { status: 'available' }) |
The component with its props |
| A component with slots | h(BasePanel, null, { default: () => 'Content', footer: () => h('p', 'Footer') }) |
Slots as functions |
| Several children without a wrapper | [h('dt', 'Floor'), h('dd', '1')] (returning an array) |
A fragment |
The rules that change compared with templates:
propsis a single flat object with attributes, component props and events all mixed together. Vue decides what each one is: if the component declares the prop, it is a prop; if it starts withonfollowed by a capital letter, it is an event; the rest are attributes.classandstyleaccept the same forms as:classand:style(02-06): a string, an object or an array.- Events are written
onClick,onUpdate:modelValue,onSelect(on+ the event's name with its first letter capitalised). - A component's children are slots, and they are passed as an object of functions. If you pass an array or a text to a component, Vue treats it as its default slot, but with a performance warning: always use functions.
- If you skip the props but there are children, you can only omit the second argument when the children are not an object:
h('p', 'Text')works, but a slots object needs thenullin front of it, so that Vue does not mistake it for props.
- Returning a render function from
setup
setupIn a component, the render function is obtained by returning it from setup. Since <script setup> does not allow returning anything, these components are written with a normal <script> and export default, in a .vue file (which keeps <style scoped>) or in a .js file:
<script>
import { ref, h } from 'vue'
export default {
name: 'AttendeeCounter',
props: {
capacity: { type: Number, required: true }
},
setup(props, { slots, emit, attrs, expose }) {
const attendees = ref(0)
function add() {
if (attendees.value < props.capacity) attendees.value++
}
// The returned function runs on every render
return () =>
h('div', { class: 'counter' }, [
h('span', `${attendees.value} / ${props.capacity}`),
h('button', { type: 'button', onClick: add, disabled: attendees.value >= props.capacity }, '+1')
])
}
}
</script>setupruns once: it creates the state and the functions.- The returned function runs on every render, inside a reactive effect: it reads
attendees.valueandprops.capacity, and Vue repeats it when they change. That is why inside it you always readprops.capacity, not a variable destructured at the start ofsetup(which would be a copy without reactivity; 3.5's reactive destructuring only exists in<script setup>). - The second argument of
setupgives access toslots,emit,attrsandexpose, the same things you get in<script setup>withuseSlots(),defineEmits,useAttrs()anddefineExpose. expose: when it returns a render function,setupcan no longer return variables for the parent's template ref. If the component must expose something, callexpose({ reset }).
- Equivalences between templates and render functions
Every template directive has its equivalent in code. This table is the quick reference; below it you will find the cases that deserve an explanation.
| Template | Render function |
|---|---|
<p v-if="error">{{ error }}</p><p v-else>OK</p> |
error.value ? h('p', error.value) : h('p', 'OK') |
<li v-for="room in rooms" :key="room.id">{{ room.name }}</li> |
rooms.value.map((room) => h('li', { key: room.id }, room.name)) |
<button @click="book"> |
h('button', { onClick: book }) |
<button @click.stop.prevent="book"> |
h('button', { onClick: withModifiers(book, ['stop', 'prevent']) }) |
<input @keyup.enter="runSearch"> |
h('input', { onKeyup: withKeys(runSearch, ['enter']) }) |
<input v-model="text"> |
h('input', { value: text.value, onInput: (e) => (text.value = e.target.value) }) |
<TextField v-model="name" /> |
h(TextField, { modelValue: name.value, 'onUpdate:modelValue': (v) => (name.value = v) }) |
<BasePanel><template #footer>Footer</template>Content</BasePanel> |
h(BasePanel, null, { default: () => 'Content', footer: () => 'Footer' }) |
<RoomList :rooms="r"><template #room="{ room }">{{ room.name }}</template></RoomList> |
h(RoomList, { rooms: r }, { room: ({ room }) => room.name }) |
<slot name="footer" :total="total" /> (in the child) |
slots.footer?.({ total: total.value }) |
<p v-show="visible"> |
withDirectives(h('p'), [[vShow, visible.value]]) |
<input v-focus:if="signal"> |
withDirectives(h('input'), [[resolveDirective('focus'), signal.value, 'if']]) |
<RouterLink :to="..."> (global component) |
h(resolveComponent('RouterLink'), { to: ... }) or h(RouterLink, ...) by importing it |
<input ref="field"> |
h('input', { ref: field }), with const field = ref(null) |
<div v-bind="$attrs"> |
h('div', { ...attrs }) |
4.1 v-if and v-for: plain JavaScript
There are no directives: you use the ternary operator, &&, if and map. This is the main advantage of render functions: the full power of the language.
return () => {
if (loading.value) return h('p', 'Loading…')
if (rooms.value.length === 0) return h('p', 'There are no rooms.')
return h('ul', rooms.value.map((room) => h('li', { key: room.id }, room.name)))
}The key is just as important as in a template (02-08): it goes in each element's props object.
4.2 Events and modifiers
Event and key modifiers (02-04) are compiler sugar. In code, you use the withModifiers and withKeys helpers, or write the logic by hand (event.stopPropagation()). Some modifiers (.once, .capture, .passive) are expressed in the prop's name: onClickOnce, onScrollPassive.
4.3 v-model
v-model does not exist in render functions: you have to write its two halves, as in the manual implementation from 03-03. On a native element, value + onInput; on a component, modelValue + onUpdate:modelValue (or floor + onUpdate:floor for a v-model:floor).
4.4 Slots: passing them and rendering them
There are two sides:
- When using a component, slots are passed as the third argument, an object whose keys are the names and whose values are functions that return VNodes. A scoped slot is a function that receives the slot's props.
- Inside the component, slots are in
slots(fromsetup) and are rendered by calling them:slots.default?.(). The?.covers the case where the parent has not filled it. To provide default content:slots.footer?.() ?? h('p', 'No footer').
Why functions? Because that way the slot's content is evaluated during the child's render, and Vue records the dependencies in the right place: if a piece of data that only the slot uses changes, the child is updated without touching the parent.
4.5 Directives: withDirectives
v-show and custom directives are applied by wrapping the VNode with withDirectives(vnode, [[directive, value, argument, modifiers]]). vShow is imported from vue; a globally registered directive of your own (such as v-focus from directivesPlugin, 07-02) is obtained with resolveDirective('focus'), or imported directly (vFocus).
4.6 Components: import them or use resolveComponent
The normal thing is to import the component and pass it to h. resolveComponent('Name') looks up a globally registered component by its name, as the template does with <RouterLink> or <i18n-t>. It must be called inside setup or the render function, never at module level, because it needs to know which application to look in.
- Functional components
A functional component is a component with no state or lifecycle, written as a plain function that receives props and returns VNodes:
// A functional component: a function, no setup, no state of its own
import { h } from 'vue'
export default function Tag(props, { slots, emit, attrs }) {
return h('span', { class: ['tag', `tag--${props.tone}`] }, slots.default?.())
}
Tag.props = {
tone: { type: String, default: 'neutral' }
}
Tag.emits = []| Normal component | Functional component | |
|---|---|---|
State (ref), computed, watch |
Yes | No: it has no setup |
| Lifecycle hooks | Yes | No |
Composables with inject (useI18n, useFormat) |
Yes | No: there is no setup context |
| Template ref from the parent | Yes | No |
| Fallthrough attributes | All of them | Only class, style and onX events if it does not declare props; all of them if it does |
| Declaration | An object with setup, or <script setup> |
A function, with props and emits as properties |
In Vue 2, functional components were used for performance, because they were much cheaper to create. In Vue 3 that difference is minimal, and the official documentation recommends normal components unless the functional form turns out to be simpler. Use them for small, purely presentational pieces: icons, separators, wrappers.
- When to use render functions and when not to
Section 1 explains the rule: the compiler knows your template and adds hints (hoisting, caching of static nodes, patch flags, blocks) that make updates much faster. A hand-written render function is arbitrary code: Vue cannot know which parts are static, so it compares the whole tree on every update.
| Use templates when... | Use render functions (or JSX) when... |
|---|---|
| The structure is fixed and the logic fits into directives (almost always) | The structure depends on data in a way that would require lots of v-if or <component :is> in a template |
| You want maximum performance without effort | The component is small and the cost of comparing does not matter |
| The team includes people closer to HTML (markup, design) | You are writing a library of highly configurable components (tables, generated forms, trees) |
You need <style scoped>, v-model and slots with the most readable syntax |
You generate components from a configuration (columns, schemas, rules) |
| You need to manipulate VNodes (cloning, wrapping, filtering a slot's children) |
For Colmena, the conclusion is clear: the vast majority of components will stay as templates. The three in this lesson are good candidates because their structure is decided with logic.
- Colmena:
SectionTitle as a render function
SectionTitle as a render functionIn 03-06 you wrote SectionTitle with <component :is="`h${level}`">, a trick to choose the tag according to a prop. In a render function, the tag is simply the first argument of h, a computed string. We will take the opportunity to add an improvement: an optional anchor link, so that a section can be linked to directly (/dashboard/invoices#outstanding).
Replace the contents of src/components/SectionTitle.vue:
<script>
// src/components/SectionTitle.vue
// A heading of variable level (h1-h6) with an optional anchor link
import { h } from 'vue'
export default {
name: 'SectionTitle',
props: {
level: {
type: Number,
default: 2,
validator: (n) => Number.isInteger(n) && n >= 1 && n <= 6
},
anchor: { type: String, default: '' } // the heading's id and the link's target
},
setup(props, { slots }) {
return () =>
h(`h${props.level}`, { id: props.anchor || undefined, class: 'section-title' }, [
slots.default?.(),
props.anchor
? h('a', { href: `#${props.anchor}`, class: 'section-title__anchor', 'aria-hidden': 'true' }, '#')
: null
])
}
}
</script>
<style scoped>
.section-title__anchor {
margin-left: 0.4rem;
color: var(--color-honey-dark);
text-decoration: none;
opacity: 0;
}
.section-title:hover .section-title__anchor,
.section-title__anchor:focus {
opacity: 1;
}
</style>`h${props.level}`: the tag is an expression. There is no need for<component :is>.id: props.anchor || undefined: withundefined, Vue does not add the attribute (as in templates, 02-03).- Children in an array with a
null: Vue ignoresnullandundefinedchildren, which lets you write conditions inside the array. aria-hiddenon the anchor: the screen reader already reads the title; the "#" is a visual aid. Keyboard users can still use the link.<script>instead of<script setup>, and the file is still a.vue: no import changes, and<style scoped>works. Vue applies thedata-v-...attribute to the elements created by the component's render function just as it does to those from a template.
Usage does not change. For example, in DashboardInvoicesView, replace the <h2>Invoices</h2>:
<SectionTitle :level="2">Invoices</SectionTitle>
<!-- and, for the outstanding amount: -->
<SectionTitle :level="3" anchor="outstanding">Outstanding</SectionTitle>
- Colmena:
DataTable, a table configurable by columns
DataTable, a table configurable by columns8.1 The problem
DashboardInvoicesView has a hand-written table: six <th>s, six <td>s with their formatting. TableView (the catalogue's table view, 03-06) has another. Each new table repeats the same structure with different columns. The idea is a component that receives the description of the columns as data:
const columns = [
{ key: 'number', title: 'Number' },
{ key: 'amount', title: 'Amount', align: 'right', format: (value) => format.price(value) }
]and that allows any cell to be customised with a slot per column, with a dynamic name: #cell-amount, #cell-paid... With a template, this requires nested v-fors, dynamic slots (<slot :name="`cell-${column.key}`">) and conditions for the formatting. With a render function it is a couple of loops.
8.2 The component
Create src/components/base/DataTable.vue:
<script>
// src/components/base/DataTable.vue
// A table configurable by columns, written with a render function.
import { h } from 'vue'
export default {
name: 'DataTable',
props: {
// [{ key, title, align?: 'right', format?: (value, row) => text }]
columns: { type: Array, required: true },
rows: { type: Array, required: true },
rowKey: { type: String, default: 'id' },
title: { type: String, default: '' },
emptyText: { type: String, default: 'No data to display.' }
},
setup(props, { slots }) {
function columnClass(column) {
return { 'data-table__cell--right': column.align === 'right' }
}
// Priority: the column's slot > format function > the value as it is
function cellContent(column, row) {
const value = row[column.key]
const cellSlot = slots[`cell-${column.key}`]
if (cellSlot) return cellSlot({ value, row, column })
return column.format ? column.format(value, row) : String(value ?? '')
}
function body() {
if (props.rows.length === 0) {
return h('tr', [
h('td', { colspan: props.columns.length, class: 'data-table__empty' }, slots.empty?.() ?? props.emptyText)
])
}
return props.rows.map((row) =>
h(
'tr',
{ key: row[props.rowKey] },
props.columns.map((column) =>
h('td', { key: column.key, class: columnClass(column) }, cellContent(column, row))
)
)
)
}
return () =>
h('table', { class: 'data-table' }, [
props.title ? h('caption', props.title) : null,
h('thead', [
h(
'tr',
props.columns.map((column) =>
h('th', { key: column.key, scope: 'col', class: columnClass(column) }, column.title)
)
)
]),
h('tbody', body())
])
}
}
</script>
<style scoped>
.data-table {
width: 100%;
border-collapse: collapse;
background: white;
}
.data-table caption {
padding: 0.5rem 0;
font-weight: bold;
text-align: left;
}
.data-table th,
.data-table td {
padding: 0.5rem;
border-bottom: 1px solid #eee;
text-align: left;
}
.data-table__cell--right {
text-align: right;
font-variant-numeric: tabular-nums;
}
.data-table__empty {
color: #666;
font-style: italic;
}
</style>Let's analyse the structure:
cellContentconcentrates the rule for each cell: if the parent has filled thecell-<key>slot, it is used; if not, the column'sformatfunction; if not, the value as text. The slot receives{ value, row, column }, so the parent can render anything with all the context.- Dynamic slot names are simply keys of an object:
slots[`cell-${column.key}`]. body()is an ordinary helper function. In a render function you can split the tree into as many functions as you like, and name them after what they render.- The
keys go on the rows (rowKey, because invoices do not have anidbut anumber) and on the cells. - Accessibility:
<caption>gives the table a name andscope="col"associates each header with its column, just as you would in a template. - The
emptyslot allows the no-data message to be customised; if it is not filled, theemptyTextprop is used.
8.3 DashboardInvoicesView with DataTable
In the script of src/views/dashboard/DashboardInvoicesView.vue (the one you left with useRequest in 09-01), add:
// DashboardInvoicesView.vue
import DataTable from '@/components/base/DataTable.vue'
import SectionTitle from '@/components/SectionTitle.vue'
import { useFormat } from '@/plugins/format.js'
const format = useFormat()
// The columns are data: not reactive, because they do not change
const columns = [
{ key: 'number', title: 'Number' },
{ key: 'date', title: 'Date', format: (value) => format.date(value, 'numeric') },
{ key: 'client', title: 'Client' },
{ key: 'description', title: 'Description' },
{ key: 'amount', title: 'Amount', align: 'right', format: (value) => format.price(value) },
{ key: 'paid', title: 'Status' }
]And in the template, replace the whole <table class="invoices">:
<DataTable
:columns="columns"
:rows="invoices"
row-key="number"
:title="`Invoices for ${month}`"
empty-text="There are no invoices this month."
:aria-busy="loading"
>
<template #cell-paid="{ value }">
<span :class="value ? 'invoice--paid' : 'invoice--pending'">
{{ value ? 'Paid' : 'Pending' }}
</span>
</template>
</DataTable>Remember that the block is already inside the <template v-else-if="invoices"> from 09-01, so invoices is never null here.
- Be careful with prop names. If you misspell one (
empty-txtinstead ofempty-text), Vue gives no error at all: it treats it as a fallthrough attribute and puts it on the<table>, and the table shows the default text. It is one of the mistakes that TypeScript (09-02) would catch in the editor. - From the outside,
DataTableis a component like any other: props, fallthrough attributes (aria-busyends up on the<table>) and scoped slots with the usual syntax. Whoever uses it neither knows nor cares how it is written inside. - The formatting arrives in the configuration (
format.price), so the table does not depend onformatPlugin: it is a base component that can be reused in any project. - The formatting follows the language:
format.pricereads the active language every time it is called, and it is called while the table is rendering, so when the language changes the cells are updated. - Delete the
.invoicesstyles from the view's<style scoped>: they now belong toDataTable. Add the status classes:
- Colmena:
EquipmentIcon, a functional component
EquipmentIcon, a functional component9.1 The icons
The cards show the equipment as text labels with a tooltip (07-01). An icon next to each name makes them quicker to scan. We will use an SVG sprite: a single file with one <symbol> per icon, referenced with <use>. Create public/img/equipment.svg:
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="projector" viewBox="0 0 24 24">
<rect x="2" y="8" width="20" height="9" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
<circle cx="8" cy="12.5" r="2.5" fill="currentColor" />
</symbol>
<symbol id="whiteboard" viewBox="0 0 24 24">
<rect x="3" y="4" width="18" height="12" fill="none" stroke="currentColor" stroke-width="2" />
<path d="M8 20l4-4 4 4" fill="none" stroke="currentColor" stroke-width="2" />
</symbol>
<symbol id="screen" viewBox="0 0 24 24">
<rect x="2" y="4" width="20" height="13" rx="1" fill="none" stroke="currentColor" stroke-width="2" />
<path d="M8 21h8M12 17v4" stroke="currentColor" stroke-width="2" />
</symbol>
<symbol id="videoconference" viewBox="0 0 24 24">
<rect x="2" y="7" width="13" height="10" rx="2" fill="none" stroke="currentColor" stroke-width="2" />
<path d="M15 11l7-4v10l-7-4z" fill="currentColor" />
</symbol>
<symbol id="microphone" viewBox="0 0 24 24">
<rect x="9" y="2" width="6" height="12" rx="3" fill="currentColor" />
<path d="M5 11a7 7 0 0 0 14 0M12 18v4" fill="none" stroke="currentColor" stroke-width="2" />
</symbol>
</svg>currentColor makes the icon take on the colour of the surrounding text. The file is in public/, next to the room photos (02-03), so it is served as it is at /img/equipment.svg and the browser downloads it only once for all the icons.
9.2 The component
An icon has no state or lifecycle: it receives a type and renders an <svg>. It is the textbook case for a functional component. Create src/components/EquipmentIcon.js:
// src/components/EquipmentIcon.js
// Icon for a type of equipment (functional component: no state or lifecycle)
import { h } from 'vue'
import { i18n } from '@/i18n.js'
export default function EquipmentIcon({ type, size, decorative }) {
// Decorative (next to a text that already names it): hidden from screen readers.
// If it stands alone, it is an image with an accessible name.
const accessibility = decorative
? { 'aria-hidden': 'true', focusable: 'false' }
: { role: 'img', 'aria-label': i18n.global.t(`equipment.${type}.name`) }
return h(
'svg',
{ class: 'equipment-icon', width: size, height: size, viewBox: '0 0 24 24', ...accessibility },
[h('use', { href: `/img/equipment.svg#${type}` })]
)
}
EquipmentIcon.props = {
type: { type: String, required: true },
size: { type: Number, default: 16 },
decorative: { type: Boolean, default: false }
}- The props arrive as the function's first argument, already resolved with their default values, because we have declared them in
EquipmentIcon.props. i18n.global.tinstead ofuseI18n(): a functional component has nosetup, so it cannot call composables that useinject. The global translator fromsrc/i18n.js(07-03) works anywhere and, because it is called during rendering, the icon is updated when the language changes.decorativeresolves accessibility according to the context: next to the word "Projector", the icon must not be read out again; on its own, it must have a name.- Fallthrough attributes: since it declares
props, any attribute the parent passes to it (aclass, adata-test) is added to the<svg>, just as with a normal component.
9.3 Using it in RoomCard
In the template of src/components/RoomCard.vue, inside each equipment label:
<!-- RoomCard.vue: the equipment labels -->
<span v-tooltip="$t(`equipment.${item}.description`)" class="card__chip" tabindex="0">
<EquipmentIcon :type="item" decorative />
{{ $t(`equipment.${item}.name`) }}
</span>From the template, a functional component is used in exactly the same way as any other.
- JSX with
@vitejs/plugin-vue-jsx
@vitejs/plugin-vue-jsx10.1 What it is and how to set it up
JSX is an extension of JavaScript syntax that lets you write HTML-like tags inside your code. It was popularised by React, but it is not exclusive to React: it is just another way of writing calls to h(). A compiler (in Vue, a Babel plugin built into the Vite one) transforms <h3 class="title">{name}</h3> into createVNode('h3', { class: 'title' }, [name]).
To use it in Colmena:
// vite.config.js
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [vue(), vueJsx(), vueDevTools()],
// ... resolve, unchanged
})With the plugin, Vite compiles .jsx (and .tsx) files and also the <script lang="jsx"> blocks in .vue files. Vitest uses the same configuration, so the tests understand them too.
10.2 The syntax
// Curly braces {} insert any JavaScript expression
const Greeting = (props) => <p class="greeting">Hello, {props.name}</p>
// Conditions and lists: plain JavaScript
{loading.value ? <p>Loading…</p> : <ul>{rooms.value.map((r) => <li key={r.id}>{r.name}</li>)}</ul>}
// Events and modifiers
<button onClick={book}>Book</button>
<button onClick={withModifiers(book, ['stop'])}>Book</button>
// v-model and v-show are supported by the plugin
<input v-model={text.value} />
<p v-show={visible.value}>Help</p>
// Slots: as an object of functions inside the tags, or with v-slots
<BasePanel>{{ default: () => <p>Content</p>, footer: () => <p>Footer</p> }}</BasePanel>
<BasePanel v-slots={{ header: () => <h2>Title</h2> }}>Content</BasePanel>One detail: when you write <TextField /> in JSX, the plugin uses the TextField variable if it is imported in the file; if it is not, it falls back to resolveComponent('TextField'), which will only find it if it is registered globally. Always import components.
10.3 Differences from React's JSX
If you come from React, the resemblance is misleading on some points:
| Aspect | JSX in React | JSX in Vue |
|---|---|---|
| Classes | className="card" |
class="card" (the usual HTML attribute) |
| Attributes | React's camelCase names (htmlFor, tabIndex) |
HTML names (for, tabindex), as in templates |
| Events | onClick |
onClick, the same; modifiers with withModifiers |
| Two-way binding | value + onChange |
v-model (the plugin translates it) |
| Slots / children | children and props that are functions |
An object of slot functions, or v-slots |
| State | useState and the rules of hooks |
ref/reactive in setup: render functions are repeated, setup is not |
| When it re-renders | When the component's or the parent's state changes | Only when the reactive data the function read changes (dependency tracking) |
The last row is the most important: in Vue, JSX is just the way of writing the render function. Everything else (reactivity, setup running once, composables) works as always.
10.4 DataTable in JSX
For comparison, this is the same DataTable written in JSX, inside a .vue with <script lang="jsx"> to keep the scoped styles:
<script lang="jsx">
// Variant of src/components/base/DataTable.vue written in JSX
export default {
name: 'DataTable',
props: {
columns: { type: Array, required: true },
rows: { type: Array, required: true },
rowKey: { type: String, default: 'id' },
title: { type: String, default: '' },
emptyText: { type: String, default: 'No data to display.' }
},
setup(props, { slots }) {
const columnClass = (column) => ({ 'data-table__cell--right': column.align === 'right' })
function cellContent(column, row) {
const value = row[column.key]
const cellSlot = slots[`cell-${column.key}`]
if (cellSlot) return cellSlot({ value, row, column })
return column.format ? column.format(value, row) : String(value ?? '')
}
return () => (
<table class="data-table">
{props.title && <caption>{props.title}</caption>}
<thead>
<tr>
{props.columns.map((column) => (
<th key={column.key} scope="col" class={columnClass(column)}>{column.title}</th>
))}
</tr>
</thead>
<tbody>
{props.rows.length === 0 ? (
<tr>
<td colspan={props.columns.length} class="data-table__empty">
{slots.empty?.() ?? props.emptyText}
</td>
</tr>
) : (
props.rows.map((row) => (
<tr key={row[props.rowKey]}>
{props.columns.map((column) => (
<td key={column.key} class={columnClass(column)}>{cellContent(column, row)}</td>
))}
</tr>
))
)}
</tbody>
</table>
)
}
}
</script>
<!-- <style scoped>: the same as in the h() version -->Compare the two versions. The logic is identical (cellContent, the order of priority, the keys), and the structure of the tree is easier to see in JSX, because it resembles the resulting HTML. In exchange, it adds a build dependency and one more syntax that the team must know. In Colmena we are keeping the h() version: it is a single component and it is not worth adding JSX to the project just for it. If you did the installation from section 10.1 to practise, you can keep it or undo it.
10.5 Testing these components
For Vue Test Utils there is no difference at all: mount(DataTable, { props, slots }) works in the same way with a component written with a template, with h() or with JSX. A test for DataTable, in src/components/base/__tests__/DataTable.spec.js:
// src/components/base/__tests__/DataTable.spec.js
import { describe, it, expect } from 'vitest'
import { h } from 'vue'
import { mount } from '@vue/test-utils'
import DataTable from '../DataTable.vue'
const columns = [
{ key: 'number', title: 'Number' },
{ key: 'amount', title: 'Amount', align: 'right', format: (v) => `€${v}` },
{ key: 'paid', title: 'Status' }
]
const rows = [
{ number: 'INV-1', amount: 300, paid: true },
{ number: 'INV-2', amount: 1450, paid: false }
]
describe('DataTable', () => {
it('renders the columns with their formatting and the per-column slots', () => {
const wrapper = mount(DataTable, {
props: { columns, rows, rowKey: 'number', title: 'Invoices' },
slots: { 'cell-paid': ({ value }) => h('strong', value ? 'Paid' : 'Pending') }
})
expect(wrapper.get('caption').text()).toBe('Invoices')
expect(wrapper.findAll('th').map((th) => th.text())).toEqual(['Number', 'Amount', 'Status'])
const cells = wrapper.findAll('tbody tr')[1].findAll('td')
expect(cells.map((td) => td.text())).toEqual(['INV-2', '€1450', 'Pending'])
expect(cells[1].classes()).toContain('data-table__cell--right')
})
it('shows the empty-table text spanning every column', () => {
const wrapper = mount(DataTable, { props: { columns, rows: [] } })
expect(wrapper.get('td').attributes('colspan')).toBe('3')
expect(wrapper.get('td').text()).toBe('No data to display.')
})
})Notice that the test's slot is also a function that returns a VNode: it is the native form of slots that you now know from this section. Vue Test Utils also accepts template strings in slots, as you did in 08-01.
- Try it
- The code the compiler generates. Open the Vue SFC Playground (play.vuejs.org), paste
RoomCard's template and look at the JS tab. Find the_hoisted_constants, the_cacheentries and the/* TEXT */,/* PROPS */and/* CLASS */comments. SectionTitle. In "Invoices", the title looks the same as before. Hover over "Outstanding": the "#" appears. Click it: the URL ends in#outstanding, and on reloading, the router'sscrollBehavior(04-02) takes the page to it. Inspect the heading: it has thedata-v-...attribute of the scoped styles.DataTable. The invoices table looks the same, with the amount right-aligned. Switch to September: the table's title changes. Choose a month with no invoices (January, for example): "There are no invoices this month." appears, spanning the whole row. Switch the language to Spanish: the dates and amounts change format.- Fallthrough attributes. Inspect the
<table>while another month's invoices are loading: it hasaria-busy="true", the attribute you passed to the component. - Icons. The catalogue cards show an icon before each item of equipment, in the colour of the text. With the browser's accessibility inspector, check that the
<svg>is hidden (aria-hidden) and that the label is read only once. In Vue DevTools, functional components appear in the tree like the rest. - The tests.
npm test:DataTable.spec.jsis added, and theRoomCardtests stay green with the icon inside.
Common Mistakes and Tips
- Passing a component's slots as an array or text (
h(BasePanel, null, [h('p')])). It works, with a warning and worse performance. Always use an object of functions. - Forgetting the
nullfor the props when the children are a slots object:h(BasePanel, { default: () => ... })interprets the object as props. - Destructuring
propsat the start ofsetupin a component with a render function (const { level } = props). It loses reactivity: readprops.levelinside the returned function. - Creating state inside the render function (
return () => { const isOpen = ref(false); ... }). It is recreated on every render. State goes insetup. - Calling
resolveComponentorresolveDirectiveat module level. They need to know which application to look in: call them insidesetupor the render, or import the component or directive directly. - Calling composables with
injectin a functional component. It has nosetup. Use global services (such asi18n.global) or turn it into a normal component. - Forgetting the
keys in lists generated withmap. The problem is exactly the same as withv-for. - Using render functions out of habit. You lose the compiler's optimisations and readability for anyone coming from HTML. Keep them for components whose structure is decided with logic.
- Tip: when you are not sure how to express something with
h(), write it in a template in the Vue SFC Playground and look at the code it generates: it is the official translation.
Exercises
Exercise 1. Add sortable columns to DataTable: a column with sortable: true shows its header as a button; when it is clicked, the table is sorted by that column (ascending; a second click, descending). The sort order is the table's internal state (it is not emitted). Indicate the active order with aria-sort on the <th> ('ascending', 'descending' or 'none').
Exercise 2. Write with h() a DefinitionList component that receives an entries prop (an object like RoomsView's specSheet: { Floor: 1, Capacity: '8 people', ... }) and renders a <dl> with a <dt> and a <dd> per entry, without any wrapper element between them. If the parent fills the value slot (scoped with { key, value }), it is used to render each <dd>.
Exercise 3. Translate this template into a render function with h(), inside a setup that receives rooms (a prop) and emits select:
<ul class="list">
<li v-for="room in rooms" :key="room.id" :class="{ 'list__item--unavailable': !room.available }">
<button type="button" :disabled="!room.available" @click.stop="emit('select', room.id)">
{{ room.name }}
</button>
<StatusBadge v-if="!room.available" status="unavailable" />
</li>
</ul>Solutions
Solution 1. In DataTable's setup, add the sort state and a sorted list:
import { h, ref, computed } from 'vue'
// inside setup:
const sort = ref({ key: null, direction: 'ascending' })
const sortedRows = computed(() => {
const { key, direction } = sort.value
if (!key) return props.rows
const factor = direction === 'ascending' ? 1 : -1
return props.rows.toSorted((a, b) => {
const x = a[key]
const y = b[key]
return (typeof x === 'number' && typeof y === 'number' ? x - y : String(x).localeCompare(String(y))) * factor
})
})
function sortBy(key) {
const current = sort.value
sort.value = {
key,
direction: current.key === key && current.direction === 'ascending' ? 'descending' : 'ascending'
}
}
function header(column) {
const direction = sort.value.key === column.key ? sort.value.direction : 'none'
const content = column.sortable
? h('button', { type: 'button', class: 'data-table__sort', onClick: () => sortBy(column.key) }, column.title)
: column.title
return h(
'th',
{ key: column.key, scope: 'col', class: columnClass(column), 'aria-sort': column.sortable ? direction : undefined },
content
)
}And in the render, use header(column) in the <thead> and sortedRows.value instead of props.rows inside body() (including the empty-table check). In DashboardInvoicesView, add sortable: true to the date, client and amount columns. aria-sort is only set on the sortable columns; the button inside the <th> makes it possible to sort with the keyboard.
Solution 2.
// src/components/base/DefinitionList.js
import { h } from 'vue'
export default {
name: 'DefinitionList',
props: {
entries: { type: Object, required: true }
},
setup(props, { slots }) {
return () =>
h(
'dl',
{ class: 'definition-list' },
Object.entries(props.entries).flatMap(([key, value]) => [
h('dt', { key: `t-${key}` }, key),
h('dd', { key: `d-${key}` }, slots.value?.({ key, value }) ?? String(value))
])
)
}
}flatMap returns, for each entry, an array of two VNodes, and flattens them into a single list: the equivalent of <template v-for> without a wrapper. Keys must be unique among siblings, which is why the <dt> and the <dd> have different prefixes.
Solution 3.
import { h, withModifiers } from 'vue'
import StatusBadge from '@/components/StatusBadge.vue'
export default {
props: { rooms: { type: Array, required: true } },
emits: ['select'],
setup(props, { emit }) {
return () =>
h(
'ul',
{ class: 'list' },
props.rooms.map((room) =>
h('li', { key: room.id, class: { 'list__item--unavailable': !room.available } }, [
h(
'button',
{
type: 'button',
disabled: !room.available,
onClick: withModifiers(() => emit('select', room.id), ['stop'])
},
room.name
),
!room.available ? h(StatusBadge, { status: 'unavailable' }) : null
])
)
)
}
}Each directive has its translation: v-for → map with key; :class → the same object syntax in class; :disabled → the disabled prop; @click.stop → onClick with withModifiers; v-if → a ternary with null; {{ }} → the text as a child.
Conclusion
A Vue template is compiled into a render function that returns VNodes, enriched with optimisation hints (cached static nodes, patch flags, blocks) that a hand-written function does not have. With h(type, props, children) you can write those functions yourself: v-if and v-for become plain JavaScript, events become onX props (with withModifiers and withKeys), v-model its two halves, slots objects of functions that are called with slots.name?.(), directives withDirectives and global components resolveComponent. Functional components are stateless functions for small pieces, and JSX, with @vitejs/plugin-vue-jsx, is another syntax for the same thing, with notable differences from React. In Colmena, SectionTitle chooses its tag and its anchor with a render function, DataTable renders the invoices from a column configuration with a slot per column, and EquipmentIcon is a functional component that accompanies each card's equipment. The rule to take away: templates by default, render functions when the structure is decided with logic.
You have seen that Vue compares the previous VNode tree with the new one in order to apply only the changes. But there are changes the user should see happening, instead of having them appear all at once: a notification arriving, a menu opening, a cancelled booking leaving the list, one screen giving way to another. Vue has components specifically for animating elements entering and leaving the DOM, which we will study in Transitions and Animations.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
