iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0
Vue.js

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

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

  • 分享至 

  • xImage
  •  

今天要延續昨天的 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)
https://ithelp.ithome.com.tw/upload/images/20250829/20178296tsRRivs8lG.png

<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++)

https://ithelp.ithome.com.tw/upload/images/20250829/20178296bI5XHRAjqh.png

ref:
https://zh-hk.vuejs.org/guide/essentials/list.html#v-for-with-an-object


上一篇
Vue.js 新手入門之路 - 清單(串列)渲染
下一篇
Vue.js 新手入門之路 - 事件處理
系列文
Vue.js 新手入門之路15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言