Vue学习之x-template

Vue学习之x-template

今天,我们来讲一个比较有趣的一个功能吧
先来看一段代码示例:

 <html>
<head>
    <meta charset="utf-8">
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <my-component></my-component>
        <script type="text/x-template" id="my-component">
            <div>
                <p>This is the content of component</p>
                <p>Hello Vue!</p>
            </div>

        </script>
    </div>
        <script>
            Vue.component('my-component',{
                    template:'#my-component'
            });
            var app=new Vue({
                el:"#app"
            });
        </script>
    </body>
    </html>

不知大家有没有注意到,第一个“< script>”中type是x-template。
这是一种比较有用的功能。如果在声明一个组件时,在template中定义模板,如果要换行的话,要加上一个“\”,如果是比较简单的模板还好,如果比较多的话,就会感觉眼花缭乱的,因此我们有一个看起来舒服的方式:x-template

只要写出< script type=”text/x-template” id=”x-template” >< /script> 在其中间就可以愉快的写HTML代码了。不用考虑换行等问题。这里注意,要加一个id名称,并将其赋给template.然后在声明的组件中加一个:

Vue.component('my-complate',{
                                template:'#x-template'
                               })

不过,Vue的初衷并不是滥用它,因为它将模板与组件的其他定义分离了。因此,我们可以用它来开发一些中小型产品,这是比较方便的。
但据我观察,只能显示处于一个块中的,

<html>
<head>
    <meta charset="utf-8">
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <my-component></my-component>
        <script type="text/x-template" id="my-component">

                <div>
                <p>This is the content of component</p>
                <p>Hello Vue!</p>
            </div>

        </script>
    </div>
        <script>
            Vue.component('my-component',{
                    template:'#my-component'
            });
            var app=new Vue({
                el:"#app"
            });
        </script>
    </body>
    </html>

以上会显示两行的内容。

以下只会显示第一个< div >标签内容

<html>
<head>
    <meta charset="utf-8">
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <my-component></my-component>
        <script type="text/x-template" id="my-component">

                <div>
                <p>This is the content of component</p>
                <p>Hello Vue!</p>
                </div>
                <div>Hello</div>
        </script>
    </div>
        <script>
            Vue.component('my-component',{
                    template:'#my-component'
            });
            var app=new Vue({
                el:"#app"
            });
        </script>
    </body>
    </html>

原因是因为template定义的模板,一定要用一个根元素包裹起来,每个组件必须只有一个根元素,比如上例中,如果去掉< div>标签,那么就相当于有两个根元素。
(如有更详细的解释,请通知我,谢谢:)哈 )

发布了32 篇原创文章 · 获赞 10 · 访问量 3432

猜你喜欢

转载自blog.csdn.net/shandamengcheng/article/details/82710157
今日推荐