Vue进阶(幺肆玖):Vue中template标签
【摘要】 HTML5中的template标签
html5中template标签内容在页面中并不会显示。但是在后台查看页面DOM结构却存在template标签。这是因为template标签天生不可见,它设置了display:none;属性。
<!--当前页面只显示"我是自定义表现abc"这个内容,不显示"我是template",
这是因为template标签天生不可见...
HTML5中的template标签
html5
中template
标签内容在页面中并不会显示。但是在后台查看页面DOM结构却存在template
标签。这是因为template
标签天生不可见,它设置了display:none;
属性。
<!--当前页面只显示"我是自定义表现abc"这个内容,不显示"我是template",
这是因为template标签天生不可见-->
<template>
<div>我是template</div>
</template>
<abc>我是自定义表现abc</abc>
.vue 文件的基本结构如下:
<template> ........
</template>
<script> export default { name: "demo" }
</script>
<style scoped> .demo { font-size: 28px; }
</style>
上面template
标签是用来写 html 模板的,且内部必须只有一个根元素,像下面这样(不然IDE会报错)
<template> <div class="demo"> ..... </div>
</template>
但有时候我们也会看到,这样的写法,在template上使用for循环:
<template> <div class="root"> <!--在template上使用for循环--> <template v-for="item,index in 5"> <div>{{index}}---{{item}}</div> </template> </div>
</template>
下面我们一起通过浏览器dom渲染结果来看一下template是什么:
<template> <div class="root"> <template>看看外面的标签是什么</template> </div>
</template>
在浏览器中解析完的结果:
可以看到文字外面是 div.root
,所以本质上的<template>
标签并没有什么意义。template
的作用是模板占位符,可帮助我们包裹元素,但在循环过程当中,template
并不会被渲染到页面上.
我们继续看一下刚才的循环:
<template> <div class="root"> <template v-for="(item,index) in 5"> <div>测试{{index}}</div> </template> </div>
</template>
浏览器解析后的效果:
不使用template,我们也可以这样写:
<template> <div class="root"> <div v-for="item,index in 5"> <div>测试{{index}}</div> </div> </div>
</template>
但是这样循环出来会多出一层div来。
当我们不需要这外层的 div 的时候,我们可以采用上面 的方法,在 <template>
标签上使用 v-for
来循环。或者这样写:
<template> <div class="root"> <div v-for="item,index in 5" :key="index">测试{{index}}</div> </div>
</template>
注意
vue
实例绑定的元素内部的template
标签不支持v-show
指令,即v-show="false"
对template
标签来说不起作用。但是此时的template
标签支持v-if
、v-else-if
、v-else
、v-for
这些指令。
文章来源: shq5785.blog.csdn.net,作者:No Silver Bullet,版权归原作者所有,如需转载,请联系作者。
原文链接:shq5785.blog.csdn.net/article/details/111033797
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)