Vue Render Functions

Dec 3, 2019

Vue's render functions let you build components using JSX, React's superset of JavaScript. One of the reasons why Vue is so compelling is that you can build a Vue app with vanilla JavaScript - you don't necessarily need JSX. But if you're upgrading from React to Vue, using Vue's render functions can make the switch more comfortable.

Hello, Render Functions

You can create a Vue component that has a render function. When it needs to render the component, Vue calls the render() function with a single parameter: the createElement() function.

const app = new Vue({
  data: () => ({ user: 'World' }),
  render: function(createElement) {
    // `this` refers to the Vue instance, so you can
    // edit data.
    return createElement('h1', 'Hello, ' + this.user);
  }
});

Using JSX

The createElement() function is similar to React's top-level createElement() function. That means a transpiler like [Babel](https://babeljs.io/docs/en/babel-plugin-transform-react-jsx can convert the below JSX Vue instance to the previous example.

/** @jsx createElement */

const app = new Vue({
  data: () => ({ user: 'World' }),
  render: function(createElement) {
    return (<h1>{this.user}</h1>);
  }
});

Note that the @jsx pragma comment above must line up with the createElement() function name. That comment tells the transpiler what function to use when transpiling JSX to createElement() calls.

Data Input

You can't use built-in Vue directives like v-for and v-model with render functions. What you can do is use the 2nd parameter to createElement() to define on handlers.

const app = new Vue({
  data: () => ({ count: 0 }),
  render: function(createElement) {
    return createElement('div', null, [
      createElement('h1', 'Count: ' + this.count),
      // Note that the **2nd** parameter is the `data` object. Otherwise,
      // `on` won't work.
      createElement('button', {
        domProps: {
          innerHTML: 'Increment'
        },
        on: { click: () => ++this.count }
      })
    ]);
  }
});

With the above example, you can click the 'Increment' button to increase the count property.


More Vue Tutorials