我們知道 .vue 文件的基本結構是:
<template> ........ </template> <script> export default { name: "demo" } </script> <style scoped> .demo { font-size: 28px; } </style>
上面template標簽,我們都知道是用來寫 html 模板的,且內部必須只有一個根元素,像這樣(不然報錯)
<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>
下面我們來看一下template是什么:
<template> <div class="root"> <template>看看外面的標簽是什么</template> </div> </template>
在瀏覽器中解析完的結果:
可以看到文字外面是 div.root ,所以本質上的<template>標簽並沒有什么意義。
所以我們再來看一下剛才的循環:
<template> <div class="root"> <template v-for="item,index in 5"> <div>測試{{index}}</div> </template> </div> </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>
完!