首頁  >  問答  >  主體

在Vue中如何根據數據增加圖標數量

我發送了一個API請求並獲得了不同數量的參與者(從1到5)。根據這個數量,在模態框中應該會顯示對應數量的圖示。如果有3個參與者,則模態框中應該有3個使用者圖示。 我知道如何在React中實現,但我開始學習Vue3,不知道該怎麼做。

<template>
  <p>
        参与者:
            <span> 
                <UserIcon />
           </span>
  </p>
</template>


 <script lang="ts">
    import { defineComponent } from '@vue/runtime-core';
    import {HeartIcon, UserIcon, XIcon } from '@heroicons/vue/solid'
    
    export default defineComponent({
        name: 'NewActivityModal',
        components: {HeartIcon, UserIcon, XIcon},
        props: {
            randomActivity: {
                type: Object,
                required: true,
            }
        },            
    })
    
      </script>

在React中,我會這樣寫。但在Vue中該如何重寫?明確一下,該放在哪裡?

const participants = [
    <span>
      {userIcon}
    </span>,
  ];
  randomActivity.map((item) => {
    for (let i = 1; i < item.participants; i++) {
      participants.push(
        <span className="inline-block" key={`personIcon${i}`}>
          {userIcon}
        </span>
      );
    }
    return participants;
  });
P粉832490510P粉832490510282 天前354

全部回覆(2)我來回復

  • P粉647449444

    P粉6474494442024-01-11 13:52:23

    感謝 @tho-masn 的幫助,我能夠理解並重新編寫計算屬性

    numberOfParticipants () {           
            let participants = 1
            for(let i=1; i < this.randomActivity.participants; i++) {
              participants += 1;
            }       
            return participants
          }

    回覆
    0
  • P粉434996845

    P粉4349968452024-01-11 09:05:25

    首先,您需要建立一個計算屬性,該屬性傳回參與者的數量(循環的計數器 x)。

    然後,您使用該計算屬性執行循環 x 次。

    這是您想要實現的嗎?

    <template>
      <p>
        参与者:
        <span
          v-for="counter in numberOfParticipants"
          :key="counter"
        > 
          <UserIcon />
        </span>
      </p>
    </template>
    
    
    <script lang="ts">
      import { defineComponent } from '@vue/runtime-core';
      import {HeartIcon, UserIcon, XIcon } from '@heroicons/vue/solid'
      
      export default defineComponent({
        name: 'NewActivityModal',
        components: {HeartIcon, UserIcon, XIcon},
        props: {
          randomActivity: {
              type: Object,
              required: true,
            }
          }
        }, 
        computed: {
          numberOfParticipants () {
            return randomActivity
              .map(item => {
                return item.participants
              })
              .flat()
              .length
          }    
        } 
      })
    </script>
    

    回覆
    0
  • 取消回覆