What are render functions in VueJS?

Vue is an open-source JavaScript front-end framework used to develop web applications’ user interfaces (UI). The render function in Vue returns a virtual Document Object Model (vDOM) node, which is then written into real DOM, also known as browser DOM, and this node is commonly called VNode. These nodes, returned by render functions, are compared with the previous vDOM, and only new elements are updated, enhancing performance.

Render function() flow
Render function() flow

Syntax

Any Vue component can have the implementation of the render function. The syntax of a render function is like this:

render() {
return 'hello world!'
}

We can render a string, array, component, or any other element. We will understand it more with the help of an example.

Example 1

Let's try to render a simple <p> tag with the help of the render function:

import Vue from 'vue'
Vue.config.productionTip = false
new Vue({
  el: '#app',
  render(createElement) {
    return createElement('p', 'Hello,this is a rendered paragraph');
  }
});
VueJs Code

Explanation

  • Line 5: The render function is returning an interface of the <p> tag. This will be changed to real DOM when we hit the RUN button.

  • Line 6: As discussed earlier, the render function returns a VNode, which is implemented into real DOM.

Example 2

We will dive deeper into the render function to better understand it. This time we will try to render multiple HTML elements.

import Vue from 'vue'
Vue.config.productionTip = false
// import { h } from 'vue'
new Vue({
  el: '#app',
  render(createElement) {
    const heading=createElement('h1','Welcome to Educative!');
    const paragraph=createElement('p',{style: { color: 'red' } },'Pleasure to meet you. Lets learn Vue together.')
    return createElement('div',[heading, paragraph])
    }
});
VueJs Code

Explanation

  • Line 7–8: We are creating <h1> and <p> and storing them for later use. The important thing to note here is that we are simply creating and not using these variables.

  • Line 9: The render function return value is basically a <div> that has two child nodes i.e., <h1> and <p>.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved