Render Functions & JSX
Vue recommends using templates to build applications in the vast majority of cases. However, there are situations where we need the full programmatic power of JavaScript. That's where we can use the render function.
If you are new to the concept of virtual DOM and render functions, make sure to read the Rendering Mechanism chapter first.
Basic Usage
Creating Vnodes
Vue provides an h() function for creating vnodes:
import { h } from 'vue'
const vnode = h(
'div', // type
{ id: 'foo', class: 'bar' }, // props
[
/* children */
]
)
h() is short for hyperscript - which means "JavaScript that produces HTML (hypertext markup language)". This name is inherited from conventions shared by many virtual DOM implementations. A more descriptive name could be createVNode(), but a shorter name helps when you have to call this function many times in a render function.
The h() function is designed to be very flexible:
// all arguments except the type are optional
h('div')
h('div', { id: 'foo' })
// both attributes and properties can be used in props
// Vue automatically picks the right way to assign it
h('div', { class: 'bar', innerHTML: 'hello' })
// props modifiers such as `.prop` and `.attr` can be added
// with `.` and `^` prefixes respectively
h('div', { '.name': 'some-name', '^width': '100' })
// class and style have the same object / array
// value support that they have in templates
h('div', { class: [foo, { bar }], style: { color: 'red' } })
// event listeners should be passed as onXxx
h('div', { onClick: () => {} })
// children can be a string
h('div', { id: 'foo' }, 'hello')
// props can be omitted when there are no props
h('div', 'hello')
h('div', [h('span', 'hello')])
// children array can contain mixed vnodes and strings
h('div', ['hello', h('span', 'hello')])
The resulting vnode has the following shape:
const vnode = h('div', { id: 'foo' }, [])
vnode.type // 'div'
vnode.props // { id: 'foo' }
vnode.children // []
vnode.key // null
[!WARNING] Note The full
VNodeinterface contains many other internal properties, but it is strongly recommended to avoid relying on any properties other than the ones listed here. This avoids unintended breakage in case the internal properties are changed.
Declaring Render Functions
When using templates with Composition API, the return value of the setup() hook is used to expose data to the template. When using render functions, however, we can directly return the render function instead:
import { ref, h } from 'vue'
export default {
props: {
/* ... */
},
setup(props) {
const count = ref(1)
// return the render function
return () => h('div', props.msg + count.value)
}
}
The render function is declared inside setup() so it naturally has access to the props and any reactive state declared in the same scope.
In addition to returning a single vnode, you can also return strings or arrays:
export default {
setup() {
return () => 'hello world!'
}
}
import { h } from 'vue'
export default {
setup() {
// use an array to return multiple root nodes
return () => [
h('div'),
h('div'),
h('div')
]
}
}
[!TIP] Make sure to return a function instead of directly returning values! The
setup()function is called only once per component, while the returned render function will be called multiple times.
We can declare render functions using the render option:
import { h } from 'vue'
export default {
data() {
return {
msg: 'hello'
}
},
render() {
return h('div', this.msg)
}
}
The render() function has access to the component instance via this.
In addition to returning a single vnode, you can also return strings or arrays:
export default {
render() {
return 'hello world!'
}
}
import { h } from 'vue'
export default {
render() {
// use an array to return multiple root nodes
return [
h('div'),
h('div'),
h('div')
]
}
}
If a render function component doesn't need any instance state, they can also be declared directly as a function for brevity:
function Hello() {
return 'hello world!'
}
That's right, this is a valid Vue component! See Functional Components for more details on this syntax.
Vnodes Must Be Unique
All vnodes in the component tree must be unique. That means the following render function is invalid:
function render() {
const p = h('p', 'hi')
return h('div', [
// Yikes - duplicate vnodes!
p,
p
])
}
If you really want to duplicate the same element/component many times, you can do so with a factory function. For example, the following render function is a perfectly valid way of rendering 20 identical paragraphs:
function render() {
return h(
'div',
Array.from({ length: 20 }).map(() => {
return h('p', 'hi')
})
)
}
Using Vnodes in <template>
<script setup>
import { h } from 'vue'
const vnode = h('button', ['Hello'])
</script>
<template>
<!-- Via <component /> -->
<component :is="vnode">Hi</component>
<!-- Or directly as element -->
<vnode />
<vnode>Hi</vnode>
</template>
A vnode object has been declared in setup(), you can use it like a normal component for rendering.
[!WARNING] A vnode represents an already created render output, not a component definition. Using a vnode in
<template>does not create a new component instance, and the vnode will be rendered as-is.This pattern should be used with care and is not a replacement for normal components.
JSX / TSX
JSX is an XML-like extension to JavaScript that allows us to write code like this:
const vnode = <div>hello</div>
Inside JSX expressions, use curly braces to embed dynamic values:
const vnode = <div id={dynamicId}>hello, {userName}</div>
create-vue and Vue CLI both have options for scaffolding projects with pre-configured JSX support. If you are configuring JSX manually, please refer to the documentation of @vue/babel-plugin-jsx for details.
Although first introduced by React, JSX actually has no defined runtime semantics and can be compiled into various different outputs. If you have worked with JSX before, do note that Vue JSX transform is different from React's JSX transform, so you can't use React's JSX transform in Vue applications. Some notable differences from React JSX include:
- You can use HTML attributes such as
classandforas props - no need to useclassNameorhtmlFor. - Passing children to components (i.e. slots) works differently.
Vue's type definition also provides type inference for TSX usage. When using TSX, make sure to specify "jsx": "preserve" in tsconfig.json so that TypeScript leaves the JSX syntax intact for Vue JSX transform to process.
JSX Type Inference
Similar to the transform, Vue's JSX also needs different type definitions.
Starting in Vue 3.4, Vue no longer implicitly registers the global JSX namespace. To instruct TypeScript to use Vue's JSX type definitions, make sure to include the following in your tsconfig.json:
{
"compilerOptions": {
"jsx": "preserve",
"jsxImportSource": "vue"
// ...
}
}
You can also opt-in per file by adding a /* @jsxImportSource vue */ comment at the top of the file.
If there is code that depends on the presence of the global JSX namespace, you can retain the exact pre-3.4 global behavior by explicitly importing or referencing vue/jsx in your project, which registers the global JSX namespace.
Render Function Recipes
Below we will provide some common recipes for implementing template features as their equivalent render functions / JSX.
v-if
Template:
<div>
<div v-if="ok">yes</div>
<span v-else>no</span>
</div>
Equivalent render function / JSX:
h('div', [ok.value ? h('div', 'yes') : h('span', 'no')])
<div>{ok.value ? <div>yes</div> : <span>no</span>}</div>
h('div', [this.ok ? h('div', 'yes') : h('span', 'no')])
<div>{this.ok ? <div>yes</div> : <span>no</span>}</div>
v-for
Template:
<ul>
<li v-for="{ id, text } in items" :key="id">
{{ text }}
</li>
</ul>
Equivalent render function / JSX:
h(
'ul',
// assuming `items` is a ref with array value
items.value.map(({ id, text }) => {
return h('li', { key: id }, text)
})
)
<ul>
{items.value.map(({ id, text }) => {
return <li key={id}>{text}</li>
})}
</ul>
h(
'ul',
this.items.map(({ id, text }) => {
return h('li', { key: id }, text)
})
)
<ul>
{this.items.map(({ id, text }) => {
return <li key={id}>{text}</li>
})}
</ul>
v-on
Props with names that start with on followed by an uppercase letter are treated as event listeners. For example, onClick is the equivalent of @click in templates.
h(
'button',
{
onClick(event) {
/* ... */
}
},
'Click Me'
)
<button
onClick={(event) => {
/* ... */
}}
>
Click Me
</button>
Event Modifiers
For the .passive, .capture, and .once event modifiers, they can be concatenated after the event name using camelCase.
For example:
h('input', {
onClickCapture() {
/* listener in capture mode */
},
onKeyupOnce() {
/* triggers only once */
},
onMouseoverOnceCapture() {
/* once + capture */
}
})
<input
onClickCapture={() => {}}
onKeyupOnce={() => {}}
onMouseoverOnceCapture={() => {}}
/>
For other event and key modifiers, the withModifiers helper can be used:
import { withModifiers } from 'vue'
h('div', {
onClick: withModifiers(() => {}, ['self'])
})
<div onClick={withModifiers(() => {}, ['self'])} />
Components
To create a vnode for a component, the first argument passed to h() should be the component definition. This means when using render functions, it is unnecessary to register components - you can just use the imported components directly:
```js import Foo from './Foo.vue' import Bar from './Bar.jsx'
