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
的,挺直觀、也算好理解
我們也可以同時搭配索引來控制,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>
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>
今日進度先停在這邊,明天繼續加油
ref:
https://zh-hk.vuejs.org/guide/essentials/list.html