vue渲染方式:render和template的区别
template----html的方式做渲染
render----js的方式做渲染
render(提供)是一种编译方式
render里有一个函数h,这个h的作用是将单文件组件进行虚拟DOM的创建,然后再通过render进行解析。
h就是createElement()方法:createElement(标签名称,属性配置,children)
template也是一种编译方式,但是template最终还是要通过render的方式再次进行编译。
区别:
1、render渲染方式可以让我们将js发挥到极致,因为render的方式其实是通过createElement()进行虚拟DOM的创建。逻辑性比较强,适合复杂的组件封装。
2、template是类似于html一样的模板来进行组件的封装。
3、render的性能比template的性能好很多
4、render函数优先级大于template
案例一:template和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>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
Vue.component("h-title",{
/* template渲染 */
// template:`
// <div>
// <h1 v-if="level==1"><slot></slot></h1>
// <h2 v-else-if="level==2"><slot></slot></h2>
// <h3 v-else-if="level==3"><slot></slot></h3>
// </div>
// `,
/* render渲染 */
render:function(h){
// createElement(标签名称,属性配置,children)
return h("h"+this.level,
{
attrs:{
"data-id":10
}
},
// 相当于<slot></slot>标签接收
this.$slots.default
)
},
props:{
level:{
type:String
}
}
});
let vm=new Vue({
el:"#app"
});
</script>
</body>
</html>
案例二:render方式模拟button:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin: 0;padding: 0;}
.btn{
width: 80px;
line-height: 40px;
text-align: center;
color:#fff;
border-radius: 5px;
background-color: #ccc;
}
.success{background-color: green;}
.error{background-color: red;}
.info{background-color: pink;}
</style>
</head>
<body>
<div id="app">
<wql-button type="success">成功</wql-button>
<wql-button type="info">提示</wql-button>
<wql-button type="error">报错</wql-button>
<wql-button>默认</wql-button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component("wql-button",{
render:function(h){
return h("div",{
class:{
btn:true,
success:this.type=="success",
error:this.type=="error",
info:this.type=="info"
}
},this.$slots.default);
},
props:{
type:{
type:String
}
}
});
let vm=new Vue({
el:"#app"
});
</script>
</body>
</html>

浙公网安备 33010602011771号