Vue中的template标签的使用和在template标签上使用v-for
我们知道 .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>
标签:
vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)