render相对于template更加灵活!
目标
写一个组件,功能是根据传入的prop值,还决定到底是h1,....h6
<my-headeing :level="1">标题1</my-heading> ---> <h1>标题1</h1>
<my-headeing :level="6">标题6</my-heading> ---> <h6>标题6</h6>
用template来做
<template>
<div>
<h1 v-if="level===1"><slot /></h1>
<h2 v-if="level===2"><slot /></h2>
<h3 v-if="level===3"><slot /></h3>
<h4 v-if="level===4"><slot /></h4>
<h5 v-if="level===5"><slot /></h5>
<h6 v-if="level===6"><slot /></h6>
</div>
<!-- <h2></h2> -->
</template>
<script>
export default {
props: {
level: {
type: Number,
default: 1
}
}
}
</script>
用render实现
<script>
export default {
props: {
level: {
type: Number,
default: 1
}
},
render: function(h) {
// 如何在render中获取插槽的内容?
// 答:this.$slots中自动收集所有的插槽的内容
console.log('this.$slots', this.$slots.default)
console.log('在render获取level', this.level)
// render函数在执行时,会自动传入实参,实参就是createElement这个函数
// 格式:
// h(
// 参数1:标签名,或者组件选项对象 ,
// 参数2:对参数1中的标签的属性设置
// 参数3:参数1的子元素, 也可以是一个Vnode数组
// )
console.log(h)
// <h1>abc</h1>
// return h('div', { 'class': 'mydiv' }, '我是div的内容')
return h('h' + this.level, this.$slots.default)
}
}
</script>