Vue---组件模板抽离

一.为什么要组件模板抽离

我们作为计算机专业的IT人员,十分注意代码的质量,比如笔者非常赞同雷军写代码要写“诗一样的代码”,我们在上一篇《Vue—主件详解》就通过语法糖简化了我们的注册过程,但是我们通过观察,发现在Vue中写Html代码显然有些臃肿,所以我们想到可以通过模板抽离的方法将我们在Vue中的Html代码或是其他模板分离出来,使得我们的代码更加整洁。
在这里插入图片描述
没有使用组件模板分离前的实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src = "../../js/vue.js"></script>
</head>
<body>
    <div id = "app">
        <!--使用组件-->
        <my-button></my-button>
        <my-button></my-button>
        <my-button></my-button>
    </div>
    <script type = "text/javascript">

        //创建组件构造器
        //注册组件
        Vue.component('myButton',{
            template:
                `<h1>
                    Good Morning
                </h1>`
        })

        const app = new Vue({
            el:"#app",
            data:{

            }
        })
    </script>
</body>
</html>

我们共有两种模板分离的写法。


二.使用<script>标签

语法详解:

(1) 使用<script></script>将我们的模板包裹起来,注意type为text/x-template,然后要给模板起一个id,不然我们的主件不能挂载在组件上。
在这里插入图片描述

(2)只需将模板与组件联系就好了。
在这里插入图片描述
使用<script>标签 的实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src = "../../js/vue.js"></script>
</head>
<body>
<script type = "text/x-template" id = "myTemplate">
    `<h1>
        Good Morning
    </h1>`
</script>
<div id = "app">
    <!--使用组件-->
    <my-button></my-button>
    <my-button></my-button>
    <my-button></my-button>
</div>
<script type = "text/javascript">

    //创建组件构造器
    //注册组件
    Vue.component('myButton',{
        template:"#myTemplate"
    })

    const app = new Vue({
        el:"#app",
        data:{

        }
    })
</script>
</body>
</html>

三.使用<template>标签

与<script>标签 差不多,这里就不重复了。
在这里插入图片描述

在这里插入图片描述
实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src = "../../js/vue.js"></script>
</head>
<body>
<template id = "myTemplate">
    `<h1>
         Good Morning
    </h1>`
</template>
<div id = "app">
    <!--使用组件-->
    <my-button></my-button>
    <my-button></my-button>
    <my-button></my-button>
</div>
<script type = "text/javascript">

    //创建组件构造器
    //注册组件
    Vue.component('myButton',{
        template: "#myTemplate"
    })

    const app = new Vue({
        el:"#app",
        data:{

        }
    })
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值