If you’ve been working with Vue for a while, you may have come across this way of rendering your app — this is the default in the latest version of the CLI, in main.js
:
new Vue({
render: h => h(App)
}).$mount('#app')
Or, if you’re using a render function, possibly to take advantage of JSX:
Vue.component('jsx-example', {
render (h) {
return <div id="foo">bar</div>
}
})
You may be wondering, what does that h
do? What does it stand for? The h
stands for hyperscript. It’s a riff of HTML, which means Hypertext Markup Language: since we’re dealing with a script, it’s become convention in virtual DOM implementations to use this substitution. This definition is also addressed in the documentation of other frameworks as well. Here it is, for example, in Cycle.js.
In this issue, Evan describes that:
Hyperscript itself stands for “script that generates HTML structures”
This is shortened to h
because it’s easier to type. He also describes it a bit more in his Advanced Vue workshop on Frontend Masters.
Really, you can think of it as being short for createElement
. Here would be the long form:
render: function (createElement) {
return createElement(App);
}
If we replace that with an h
, then we first arrive at:
render: function (h) {
return h(App);
}
…which can then be shortened with the use of ES6 to:
render: h => h (App)
The Vue version takes up to three arguments:
render(h) {
return h('div', {}, [...])
}
- The first is type of the element (here shown as
div
). - The second is the data object. We nest some fields here, including: props, attrs, dom props, class and style.
- The third is an array of child nodes. We’ll then have nested calls and eventually return a tree of virtual DOM nodes.
There’s more in-depth information in the Vue Guide here.
The name hyperscript may potentially be confusing to some people, given the fact that hyperscript is actually the name of a library (what isn’t updated these days) and it actually has a small ecosystem. In this case, we’re not talking about that particular implementation.
Hope that clears things up for those who are curious!
Does that style have any advantages over the one I use? I’ve seen the ‘render (h) style in examples but not in any production code I’ve worked with.
main.js:
and in a component:
The h() way allows you to programmatically control your rendering. Basically, it’s a low-level option if you need finer control or need to scale your Vue.js view/app for a very large number of users. It’s an optimization.
The code you showed is the standard way (the way the Vue.js documentation initially teaches), which is easier to read for non-programmers.
Evan You wanted Vue.js to be approachable to many users but also have features for developers wanting more control.
Why bother shortening it. It can only create confusion. Keep variable/parameter names as clear as possible in code and let your build process save you the bytes in production
It’s a big messy world out there. C’est la vie, dude.