render函数初步了解
-
template下只允许有一个子节点
小栗子:
使用render函数就会省事很多:栗子进行对比:
<div id="app">
<child :level="level">
我是一个痴人
</child>
</div>
<template id="hdemo">
<div>
<h1 v-if="level==1">
<slot></slot>
</h1>
<h2 v-if="level==2">
<slot></slot>
</h2>
<h3 v-if="level==3">
<slot></slot>
</h3>
</div>
</template>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
// 自定义指令 使用Vue组件定义:
// Vue.component('child', {
// props: ['level'],
// template: `#hdemo`
// });
// 使用render函数定义
Vue.component("child", {
render: function(createElement) {
return createElement('h' + this.level, this.$slots.default)
},
props: ['level']
})
var app = new Vue({
el: '#app',
data: {
level: 3
}
})
</script>
render函数的第一个参数
在render
函数的方法中,参数必须是createElement
,createElement
的类型是function
render
函数的第一个参数可以是 String | Object | Function
小栗子:
<div id="app">
<child></child>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
Vue.component("child", {
// 第一个参数必选
// --- String --- html标签
// ---Object ---一个含有数据选项的对象
// ---Function ---方法返回含有数据选项的对象
render: function(createElement) {
// `createElement`的类型是`function`
alert(typeof createElement)
// String-- - html标签
// return createElement('div')
// Object 一个含有数据选项的对象
// return createElement({
//