Understanding Vue.js Render Functions

In Vue.js, components can define their structure using either templates or render functions. While templates are more declarative and resemble HTML, render functions offer a programmatic way to construct the virtual DOM—closer to Vue’s internal mechanics.

From Template to Virtual DOM

When you write a template like <h1>hello world</h1>, Vue internally compiles it into a render functon. This function, when executed in the context of a Vue instance, returns a virtual node (VNode)—a lightweight JavaScript representation of a real DOM element.

You can observe this transformation using Vue.compile():

const compiled = Vue.compile('<h1>hello world</h1>');
console.log(compiled.render); // Function that returns a VNode

Calling this render function with a proper context yields a VNode object:

const vm = new Vue({});
const vnode = compiled.render.call(vm);
// vnode = { tag: 'h1', children: [...], ... }

Render Function Basics

A render function receives a single argument: createElement (often aliased as h). This function is used to describe VNodes. If both template and render are provided in a component, render takes precedence.

new Vue({
  render(createElement) {
    return createElement('h1', 'hello world');
  }
});

The Three Arguments of createElement

The createElement function accepts up to three parameters:

  1. Tag/Component: A string (e.g., 'div'), a component constructor, or an async component factory.
  2. Data Object: An object describing attributes, props, event handlers, etc.
  3. Children: Either a string (text node) or an array of child VNodes.

Example: Simple Element

createElement('h1', { class: { foo: true } }, 'hello world')

Example: Component with Props and Events

To represent <UserProfile name="Alice" @click="handleClick" />:

createElement(UserProfile, {
  props: { name: 'Alice' },
  on: { click: this.handleClick }
})

Example: Nested Structure

For <h1><span style="color:red">hello</span> <span>world</span></h1>:

render(h) {
  return h('h1', [
    h('span', { style: { color: 'red' } }, 'hello'),
    h('span', 'world')
  ]);
}

This aproach gives developers fine-grained control over the virtual DOM, enabling dynamic structures that would be cumbersome in templates. Render functions are especially useful when building reusable, abstract components or when performence optimization requires avoiding template compilation overhead.

Tags: Vue.js render function Virtual DOM VNode createElement

Posted on Thu, 22 Oct 2026 16:56:01 +0000 by sneakyimp