Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vue, what is the relationship of template, render, VNode?

During development of a vue project, and got some doubt regarding template / render / VNode.

After reading the document https://v2.vuejs.org/v2/guide/syntax.html, and google search, still didn't understand it well.


Code

main.js: (partly)

new Vue({
  el: '#app',
  render: h => h(App),
  router
})

App.vue:

<template>
  <div id="content">
    <!--    <img src="./assets/logo.png" alt="">-->
    <router-view></router-view>
  </div>
</template>

<script>
  export default {}
</script>

Questions

  • What is h from h => h(App) ?
  • And what is the type of h's return value?
  • Does the template always compile to a VNode or a function that returns a VNode?
like image 510
user218867 Avatar asked Jan 27 '23 00:01

user218867


1 Answers

What is h from h => h(App)

render: h => h(App) is shorthand for:

render: function (createElement) {
    return createElement(App);
}

where h is shorthand for the createElement argument; a function to compile the template into a VNode

https://github.com/vuejs-templates/webpack-simple/issues/29#issuecomment-312902539


What is the type of h's return value?

Since h is the createElement function, h here returns a VNode

https://v2.vuejs.org/v2/guide/render-function.html#createElement-Arguments


Does the template always compile to a VNode or a function that returns a VNode

You can do either, just depending on your implementation. If you use Vue.compile, then you can compile the template into a render function:

var res = Vue.compile('<div><span>{{ msg }}</span></div>')

new Vue({
  data: {
    msg: 'hello'
  },
  render: res.render,
  staticRenderFns: res.staticRenderFns
})

https://v2.vuejs.org/v2/api/#Vue-compile

If you use the createElement function, then you compile the template directly into a VNode.

like image 110
Nick G Avatar answered Jan 28 '23 14:01

Nick G