1.什么是render函数?
vue通过 template 来创建你的 HTML。但是,在特殊情况下,这种写死的模式无法满足需求,必须需要js的编程能力。此时,需要用render来创建HTML。
比如如下我想要实现如下html:
<div id="container"> <h1> <a href="#" rel="external nofollow" rel="external nofollow" > Hello world! </a> </h1> </div>
我们会如下使用:
<!DOCTYPE html>
<html>
<head>
<title>演示Vue</title>
<style>
</style>
</head>
<body>
<div id="container">
<tb-heading :level="1">
<a href="#" rel="external nofollow" rel="external nofollow" >Hello world!</a>
</tb-heading>
</div>
</body>
<script src="./vue.js"></script>
<script type="text/x-template" id="templateId">
<h1 v-if="level === 1">
<slot></slot>
</h1>
<h2 v-else-if="level === 2">
<slot></slot>
</h2>
</script>
<script>
Vue.component('tb-heading', {
template: '#templateId',
props: {
level: {
type: Number,
required: true
}
}
});
new Vue({
el: '#container'
});
</script>
</html>
2.例:
遇到的问题:
在工作中,我创建了一个button组件,又创建了一个button-group组件
button组件较为简单,就是一个可以输入type/size/icon等属性的button

此为渲染后结果。
然后,创建button-group组件,目标结果为

此处,不仅要在最外层包裹一层div,还要在每个button组件外层包裹一层p标签。此处,就需要使用render函数了。
既然有了render函数,就不再需要template标签了,vue文件中只需要script标签(该组件style是全局的)
button-group.vue如下
<script>
export default {
name: "XButtonGroup",
props: {
compact: { //自定义的button-group属性,影响其classname
type: Boolean,
default: true
}
},
render(createElement) {
//此处创建element
},
computed: {
groupClass() {
const className = ["field"]; //通过计算属性监听compact属性传入className
className.push(this.compact ? "has-addons" : "is-grouped");
return className;
}
}
};
</script>
接下来就要看render函数了。
render函数中的createElement方法有三个参数。第一个参数为外层标签名,第二个为外层标签的属性对象,第三个为外层标签中的内容
