在Vue中,template、render、VNode是什么关系?

Eri*_*ang 4 javascript vue.js

在一个VUE项目的开发,并得到了有关一些疑问template/ render/ VNode

看了文档https://vuejs.org/v2/guide/syntax.html,google 搜索,还是没看懂。


代码

main.js:( 部分)

new Vue({
  el: '#app',
  render: h => h(App),
  router
})
Run Code Online (Sandbox Code Playgroud)

应用程序.vue:

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

<script>
  export default {}
</script>
Run Code Online (Sandbox Code Playgroud)

问题

  • 什么是hh => h(App)
  • h的返回值的类型是什么?
  • 模板是否总是编译为 aVNode或返回 a 的函数VNode

Nic*_*k G 6

什么是hh => h(App)

render: h => h(App) 是简写:

render: function (createElement) {
    return createElement(App);
}
Run Code Online (Sandbox Code Playgroud)

wherehcreateElement参数的简写;将模板编译为 VNode 的函数

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


h的返回值的类型是什么?

既然hcreateElement函数, h这里返回一个VNode

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


模板是否总是编译为 VNode 或返回 VNode 的函数

你可以做任何一个,这取决于你的实现。如果使用Vue.compile,则可以将模板编译为渲染函数:

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

new Vue({
  data: {
    msg: 'hello'
  },
  render: res.render,
  staticRenderFns: res.staticRenderFns
})
Run Code Online (Sandbox Code Playgroud)

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

如果使用该createElement函数,则直接将模板编译为 VNode。