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>

 

完!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM