【Vue】Vue中templater与render的区别

区别:

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值