Skip to content

Render Function

Render functions are methods in Vue for programmatically creating virtual DOM (vnode). They are more flexible than templates and suitable for complex dynamic rendering scenarios.

Note

Vue 3 and Vue 2 have significant syntax differences. This guide uses Vue3 as an example. For more usage methods, refer to Vue official documentation: Vue3 | Vue2

Basic Usage

Vue provides an h() function for creating vnodes:

js
import { h } from 'vue'
const vnode = h(
  'div', // type
  { id: 'foo', class: 'bar' }, // props
  [
  /* children */
  ]
)

h() is short for hyperscript—meaning "JavaScript that produces HTML (HyperText Markup Language)". This name comes from conventions formed by 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:

js
// 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 like in templates
// in array or object form
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')


// Can omit when there are no props
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:

js
const vnode = h('div', { id: 'foo' }, [])
vnode.type // 'div'
vnode.props // { id: 'foo' }
vnode.children // []
vnode.key // null

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.