Vue中中render方法的使用详解方法的使用详解
主要为大家详细介绍了Vue中render方法的使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
先说一下对官网上demo的个人理解:
<!DOCTYPE html>
<html>
<head>
<title>Vue的render方法说明</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<child :level="1">
hello world
</child>
</div>
<script type="text/x-template" id="anchored-heading-template">
<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>
<h4 v-if="level === 4">
<slot></slot>
</h4>
<h5 v-if="level === 5">
<slot></slot>
</h5>
<h6 v-if="level === 6">
<slot></slot>
</h6>
</div>
</script>
<script type="text/javascript">
Vue.component('child', {
template: '#anchored-heading-template',
props: {
level: {
type: Number,
required: true
}
}
});
new Vue({
el: "#app"
})
</script>
</body>
</html>
虽然使用template定义组件的方法非常的直观,但是这样会造成代码过长。可以使用render的方法
<!DOCTYPE html>
<html>
<head>
<title>Vue的render方法说明</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<child :level="1">
hello world
</child>
</div>
<script type="text/javascript">
Vue.component('child', {
render:function (createElement) {
var body=this.$slots.default;
//this.$slots返回了一个组件分发下来的元素和内容
//this.$slots.default返回了具名的内容