版權聲明:本文為CSDN博主「No Silver Bullet」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/sunhuaqiang1/article/details/111033797
————————————————
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這些指令。