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>

 

posted @   当下是吾  阅读(4395)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示