Render Function ​
Render functions are Vue methods for programmatically creating virtual DOM (vnode). More flexible than templates, suitable for complex dynamic rendering scenarios.
Note
Vue 3 and Vue 2 have significant syntax differences. This article uses Vue 3 as an example. For more usage, see Vue official documentation: Vue3 | Vue2
Basic Usage
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—meaning "JavaScript that can generate HTML (HyperText Markup Language)". This name comes from conventions formed by default in many virtual DOM implementations. A more accurate name would be createVNode(), but when you need to use render functions multiple times, a shorter name saves effort.
The h() function is very flexible in usage:
// Except for type being required, all other parameters are optional
h('div')
h('div', { id: 'foo' })
// Both attributes and properties can be written in props
// Vue will automatically assign them to the correct positions
h('div', { class: 'bar', innerHTML: 'hello' })
// Property modifiers like `.prop` and `.attr`
// can be added through `.` and `^` prefixes respectively
h('div', { '.name': 'some-name', '^width': '100' })
// Classes and styles can be written in array or object form
// just like in templates
h('div', { class: [foo, { bar }], style: { color: 'red' } })
// Event listeners should be written in onXxx form
h('div', { onClick: () => {} })
// children can be a string
h('div', { id: 'foo' }, 'hello')
// When there are no props, they can be omitted
h('div', 'hello')
h('div', [h('span', 'hello')])
// children array can contain both vnodes and strings
h('div', ['hello', h('span', 'hello')])The resulting vnode has the following form:
const vnode = h('div', { id: 'foo' }, [])
vnode.type // 'div'
vnode.props // { id: 'foo' }
vnode.children // []
vnode.key // null

