vue|template和jsx的对比

678 阅读1分钟

1、本质

template和jsx本质上都是render的一种形式,不同的是,jsx的表达更加灵活,template的表达更加固定利于理解

2、对比

(1) template是一种模板语法,使用方法是mustache语法;使用方式{{msg}}

(2)jsx就是javascript一种语法扩展,使用方式使用单花括号: {msg}

3、代码

(1)使用template构建一个标题组件

<!--nav-tmpl.vue-->
<template>
    <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>
    <h4 v-else-if="level === 4">
        <slot></slot>
    </h4>
    <h5 v-else-if="level === 5">
        <slot></slot>
    </h5>
    <h6 v-else-if="level === 6">
        <slot></slot>
    </h6>
</template>
<script>
    export default {
        name:'navComp',
        props: {
            level: {
                type: Number,
                default: 1
            }
        }
    };
</script>

(2)使用jsx构建标题组件

export default {
    name: "JsxComp",
    props: {
        level: {
            type: Number,
            default: 1
        }
    },
    render: function (h) {
        const Tag = `h${this.level}`;
        return <Tag>{this.$slots.default}</Tag>;
    }

}

4、展示

image (31).png

思考💡

在完成这个项目的过程中发现h2比h1大?

//默认样式
h1 { font-size: 2em }
h2 { font-size: 1.5em }
// 浏览器的改变值
:-webkit-any(article,aside,nav,section)
:-webkit-any(article,aside,nav,section) h1 {
    font-size: 1.17em;
}

说明h1的样式规则在括号中的section以及article等标记内被某些更具体的规则所覆盖;至关重要的是,Chrome默认样式表对于h2标签没有任何此类特殊规则,因此它们总是都以相同的大小显示。因此,当被两个或更多个article或section标签包围时,h1会变得小于h2

image (32).png

参考👀

blog.csdn.net/weixin_4386…

blog.csdn.net/lvonve/arti…

www.jianshu.com/p/175a310d9…