区别:
template:html标签的方式来创建组件的 稍微更复杂一点
render是通过js的方式来创建组件的 更加灵活
例子:
要求封装一个组件,根据传入的值来显示对应的标题等级
如:
1—>h1
2—>h2
1.template的方式
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h-title level="1">标题一</h-title>
<h-title level="2">标题二</h-title>
<h-title level="3">标题三</h-title>
<h-title level="4">标题四</h-title>
<h-title level="5">标题五</h-title>
<h-title level="6">标题六</h-title>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component("h-title",{
template:`
<h1 v-if="this.level == 1"><slot></slot></h1>
<h2 v-else-if="this.level == 2"><slot></slot></h2>
<h3 v-else-if="this.level == 3"><slot></slot></h3>
<h4 v-else-if="this.level == 4"><slot></slot></h4>
<h5 v-else-if="this.level == 5"><slot></slot></h5>
<h6 v-else-if="this.level == 6"><slot></slot></h6>
`,
props:{
level:{
type:String
}
}
})
var vm = new Vue({
el:'#app'
})
</script>
2.render的方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h-title level="1">标题一</h-title>
<h-title level="2">标题二</h-title>
<h-title level="3">标题三</h-title>
<h-title level="4">标题四</h-title>
<h-title level="5">标题五</h-title>
<h-title level="6">标题六</h-title>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component("h-title",{
// render渲染方式 灵活度更大
// h:
// 参数1:标签的名称
// 参数2:选填 对象 标签的一些配置项
// 参数3:children 嵌套的节点 数组 字符串
render(h){
h == createElement
return h("h"+this.level,this.$slots.default)
},
props:{
level:{
type:String
}
}
})
var vm = new Vue({
el:'#app'
})
</script>