咱們知道 .vue 文件的基本結構是:html
<template> ........ </template> <script> export default { name: "demo" } </script> <style scoped> .demo { font-size: 28px; } </style>
上面template標籤,咱們都知道是用來寫 html 模板的,且內部必須只有一個根元素,像這樣(否則報錯)vue
<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>
在瀏覽器中解析完的結果:spa
能夠看到文字外面是 div.root ,因此本質上的<template>標籤並無什麼意義。code
因此咱們再來看一下剛纔的循環:htm
<template> <div class="root"> <template v-for="item,index in 5"> <div>測試{{index}}</div> </template> </div> </template>
瀏覽器解析後的效果:blog
能夠看出這樣寫,相似日常這樣寫:ip
<template> <div class="root"> <div v-for="item,index in 5"> <div>測試{{index}}</div> </div> </div> </template>
可是這樣循環出來會多出一層div來it
因此咱們有時候,不須要這外層的 div 因此咱們能夠採用上面 的方法,在 <template>標籤上使用 v-for來循環。或者這樣寫:
<template> <div class="root"> <div v-for="item,index in 5" :key="index">測試{{index}}</div> </div> </template>
完!