iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0
Vue.js

Vue.js 新手入門之路系列 第 8

Vue.js 新手入門之路 - 清單(串列)渲染

  • 分享至 

  • xImage
  •  

v-for 在 list 的應用

假設要顯示一個 list,又不想要寫很多的 record,此時我們就可以使用 v-for 這個語法去把我們的 data 一筆一筆地迭代出來
eg.

<script setup>
    import { ref } from 'vue'
    const person = ref([{name:'John'},{name:'Mary'},{name:'Ann'}])
</script>


<template>
    <div class="box">
        <li v-for="p in person">
            {{ p.name }}
        </li>
    </div>
</template>

<style scoped>
    .box{
        font-size: x-large;
        border: solid;
        margin-left: 850px;
        height: 120px;
        width:250px;
        padding: 25px;
    }
</style>

這邊用一個 p 去接收,把 person 裡面的物件一一迭代出來並渲染到 li 標籤,個人覺得寫法蠻像 foreach 的,挺直觀、也算好理解
https://ithelp.ithome.com.tw/upload/images/20250828/20178296s8RSv3EL97.png

我們也可以同時搭配索引來控制,index 是從 0 開始

<script setup>
    import { ref } from 'vue'
    const message = ref('Person')
    const person = ref([{name:'John'},{name:'Mary'},{name:'Ann'}])
</script>


<template>
    <div class="box">
        <li v-for="(p,index) in person">
            The {{index+1}}th {{message}} is {{ p.name }}
        </li>
    </div>
</template>

<style scoped>
    .box{
        font-size: x-large;
        border: solid;
        margin-left: 850px;
        height: 120px;
        width:300px;
        padding: 25px;
    }
</style>

https://ithelp.ithome.com.tw/upload/images/20250828/201782964tjDB7pvwX.png

v-for 也可以存取父級別的 data
這邊的 case 可以想像為

for{
    for{}
    for{}
}

這樣的感覺

<script setup>
    import { ref } from 'vue'
    const family = ref([
        {
            parent: [{name:'Mr.Chen'},{name:'Mrs.Chen'}],
            children: [{ name: 'Ming'},{ name: 'Hui' }]
        },
        {
            parent: [{name:'Mr.Wang'},{name:'Mrs.Wang'}],
            children: [{ name: 'Zhong' },{ name: 'Ann' }]
        }
        ])
    const attr = 'box'
</script>

<template>
    <div :class="attr" v-for="(f) in family">
        <li v-for="(p) in f.parent">{{ p.name }}</li>
        <li v-for="(c) in f.children">{{ c.name }}</li>
    </div>
</template>

<style scoped>
    .box{
        display: flex;
        flex-direction: column;
        justify-content: center;
        font-size: x-large;
        border: solid;
        margin-left: 650px;
        margin-top: 5px;
        height: 120px;
        width:200px;
        padding: 25px;
    }
</style>

https://ithelp.ithome.com.tw/upload/images/20250828/2017829664ReF3DqDL.png

今日進度先停在這邊,明天繼續加油

ref:
https://zh-hk.vuejs.org/guide/essentials/list.html


上一篇
Vue.js 新手入門之路 - 響應式基礎
下一篇
Vue.js 新手入門之路 - 清單渲染 (二)
系列文
Vue.js 新手入門之路15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言