Vue之x-template(1)
2024-08-30 20:27:25
今天,我们来讲一个比较有趣的一个功能吧
先来看一段代码示例:
<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>
<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 >标签内容
原因是因为template定义的模板,一定要用一个根元素包裹起来,每个组件必须只有一个根元素,比如上例中,如果去掉< div>标签,那么就相当于有两个根元素。
.
最新文章
- centos6安装svn1.9
- 寒冰王座 hdu 1248(背包)
- Labeled ContentControl &; LabeledControl【项目】
- php文本操作方法集合比较
- 我只知道一点非常简单的关于MVC的验证
- 【Android - MD】之CardView的使用
- [转]【基于zxing的编解码实战】精简Barcode Scanner篇
- [Angular 2] Validation
- C盘hosts
- servlet过滤器配置白名单、黑名单
- 使用FastClick的同时造成元素上的trigger(&#39;click&#39;)无法触发的解决办法
- Cobbler自动化部署
- 2013 多校联合 2 A Balls Rearrangement (hdu 4611)
- Centos7安装jexus,部署asp.net core,asp.net mvc
- CodeIgniter 2.x和3.x修改默认控制器问题解答
- Framework7框架结构
- 【Ansible 文档】【译文】主机清单文件
- Mysql添加和删除唯一索引、主键
- 【SqlServer】SqlServer存储过程使用
- JSON.toJSONString中序列化空字符串遇到的坑
热门文章
- 如何制作.a静态库?合成多架构静态库?
- bzoj2743 [HEOI2012]采花——树状数组+离线
- 《Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks》论文笔记
- asp.net mvc4 controller
- Linux Gcc编译错误(转载)
- bzoj 3629: [JLOI2014]聪明的燕姿【线性筛+dfs】
- A - Supercentral Point CodeForces - 165A
- nginx_uWSGI_django_virtualenv_supervisor发布web服务器
- hdu 2121 Ice_cream’s world II (无定根最小树形图)
- 题解报告:poj 2559 Largest Rectangle in a Histogram(单调栈)