前言
render函数很难啃下来,我看的头晕眼花.今天可是我生日啊,搞什么鬼!
在创建vue项目之后,main.js文件中主模板文件的配置会有两种方式:
//第一种方式:
import Vue from 'vue'
import App from './App.vue'
new Vue({
//此处的el对应的是index.html中的div标签的id
el: '#app',
components: { App },
// 此处template应该是被内部拿去使用了,没有看到显示的app标签
template: '<App/>'
});
复制代码
//第二种方式:
import Vue from 'vue'
import App from './App.vue'
new Vue({
el: '#app',
render: h => h(App)
//render函数以js的方式(虚拟节点)去渲染组件
//App是组件,是项目的主组件
})
复制代码
学到了render函数去解释一下第二种方式:
render: h => h(App)
//es6语法箭头函数的简写形式
//h又是createElement的另一种写法,这是vue规定的,没有为什么
复制代码
相当于:
render: (h) => {
return h(App)
}
复制代码
相当于:
//箭头函数转为普通函数
render: function(h) {
return h(App)
}
复制代码
相当于:
render: function(createElement) {
return createElement(App)
}
复制代码
简单演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<!--无需显示的去用MyComponent组件标签,在此处也可显示-->
</div>
<script>
let MyComponent = {
template: `
<div>子组件</div>
`
}
let vm = new Vue({
el: '#app',
render: h => h(MyComponent)
})
</script>
</body>
</html>
复制代码