今天要延續昨天的 v-for
除了迭代一般的 list
,我們也可以直接迭代一個 object
eg.
<script setup>
import { reactive } from 'vue'
const attr = 'box'
const myObject = reactive({
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2016-04-10'
})
</script>
<template>
<div :class="attr">
<li v-for="value,key in myObject">
{{key}} : {{ value }}
</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: 200px;
width:350px;
padding: 35px;
}
</style>
用 v-for
第一個參數 value
取值以及第二個參數 key
取鍵(第三個參數則是 index
)
<script setup>
import { reactive } from 'vue'
const attr = 'box'
const messege = 'for loop:'
</script>
<template>
<div :class="attr">
<p>{{ messege }}</p>
<span v-for="n in 10">{{ n }}</span>
<!-- 從 1 開始迭代而非 0 -->
</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: 450px;
width:250px;
padding: 35px;
}
</style>
我們也可以直接讓 v-for
接收數值,這樣就會像是
for(int i = 1;i <= 10;i++)
ref:
https://zh-hk.vuejs.org/guide/essentials/list.html#v-for-with-an-object