Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Advanced Vue.js - Directives, Plugins, and Render Functions Chapter 17

How to do it...


The first use case for render functions is whenever you just want a Vue instance that


displays another component.


Write an empty HTML layout, as follows:


<div id="app"></div>

We have a Greeter component somewhere that we want to show as the main Vue instance.


In the JavaScript part, add the following code:


const Greeter = {
template: '<p>Hello World</p>'
}

Here, we have to imagine that we are taking the Greeter component from somewhere else


and, since the component is nicely packaged, we don't want to modify it. Instead, we


will pass it to the Vue main instance:


const Greeter = {
template: '<p>Hello World</p>'
}
new Vue({
el: '#app',
render: h => h(Greeter)
})

If we launch the application now, we will only see the Greeter component. The main Vue


instance will only act as a wrapper.


How it works...


The render function replaces the template in the Vue instance. When render is called, the


passed argument is the so-called createElement function. We named it h for brevity. This


function accepts three arguments, but for now, just note how the first argument we are
passing (the only one we are passing) is the Greeter component.

Free download pdf