render:h => h(App) 是什么意思?

时间:2023-03-09 17:40:55
render:h => h(App) 是什么意思?

在学习vue.js时,使用vue-cli创建了一个vue项目,main.js文件中有一行代码不知道什么意思。在网上搜索得到如下解答:

参考一:https://www.cnblogs.com/longying2008/p/6408753.html

参考二:https://www.cnblogs.com/whkl-m/p/6970859.html

main.js文件内容

import Vue from 'vue'
import App from './App' Vue.config.productionTip = false // 设置false,已阻止vue在启动时生成生产提示 /* eslint-disable no-new */
new Vue({
el:'#app',
render: h => h(App)
})

 注:/* eslint-disable no-new */这不是一句注释,在js里面,new一个对象,需要赋值给某个值(变量),用Vue实例化时,不需要赋值给某值(变量),所以需要单独给配一条规则,给new Vue这行代码上面加这个注释,把这行代码规则的校验跳过,通过eslint-disable。是eslint的常用技巧之一。

言归正传:

render: h => h(App)   这是是一个箭头函数是肯定的,那对应的es5形式是怎样的呢???

  如下:

{
render: h => h(App)
}

  等价于:

{
render: h =>{
return h(App)
}
}

  等价于:

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

  即:

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

  createElement 参数

其实看了createElement的官方文档,我还是不明白createElement的用法。createElement方法的参数有几个?各个参数的含义、类型是什么?

例:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="https://unpkg.com/vue"></script>
<script type="text/javascript">
var app = new Vue({
el: '#app', // 提供一个在页面上已经存在的 DOM 元素作为 Vue 实例挂载目标
render: function (createElement) {
return createElement('h2', 'Hello Vue!');
}
});
</script>
</body>
</html>