Render是使用js的完全编程能力来渲染页面,即用js来构建DOM.
说明:render是一个方法,自带一个形参createElement(还有context..),这个参数也是一个方法,是用来创建虚拟dom节点的,也就是html模板的,然后渲染(render)到指定的节点上。render函数的目的是创建虚拟dom节点。因为createElement是个形参,所以这个形参可以用任何字符替换,比如h
createElement/h:
createElement接收3个参数:
- 第一个参数可以是HTML标签名,组件或者函数都可以;此参数是必须的;
- 第二个为数据对象,虚拟dom的配置(可选);
- 第三个为子节点,支持字符串与数组(多层嵌套h())(可选)。
写法:
render: h => h(App);
等价于
render:function(h,context){
return h(App);
}
也等价于
render:function(createElement,context){
return createElement(App);
}
在Vue实例中等价于
template:'<App></App>',
components:{App}
验证:
代码一:
<body>
<!-- 准备好一个容器-->
<div id="root">
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//定义student组件
const student = Vue.extend({
name:'student',
template:`
<div>
<h2>学生姓名:孙悟空</h2>
<h2>学生年龄:"500"</h2>
</div>
`,
})
//创建vm
new Vue({
el:'#root',
//注册组件(局部)
render: h => h(student),
})
</script>
代码二:
<body>
<!-- 准备好一个容器-->
<div id="root">
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
//定义student组件
const student = Vue.extend({
name:'student',
template:`
<div>
<h2>学生姓名:孙悟空</h2>
<h2>学生年龄:"500"</h2>
</div>
`,
})
//创建vm
new Vue({
el:'#root',
template:'<student></student>',
//注册组件(局部)
components:{student}
})
</script>
两段代码的结果如下 :
个人理解:
- Vue里的el属性:提供一个在页面上已存在的 DOM 元素作为 Vue 实例的挂载目标 ;
- 但是如果vue实例中有template属性,它会替换掉vue实例绑定的元素(即el绑定的那个元素)。
-
而且 new Vue({ el:'#root', //注册组件(局部) render: h => h(student), }) 等价于 new Vue({ el:'#root', template:'<student></student>', //注册组件(局部) components:{student} })