Home » vue » How to increase the number of icons according the fetched data in vue

How to increase the number of icons according the fetched data in vue

Posted by: admin November 26, 2021 Leave a comment

Questions:

I send an Api request and get different number of participants (from 1 to 5). According this number, the number of icons should appeared on the modal. If there are 3 participants, there should be 3 user icons in the modal.
I know how to do it in React, but I started to study Vue3 and have no idea.

<template>
  <p >
        Participants:
            <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},
        randomActivity: {
            type: Object,
            required: true,
          }
        },            
    })
    
      </script>

In React I would write in this way. But how to rewrite it in Vue? To be clear, where to put?

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;
  });
Answers:

First you create a computed property, which returns the number of participants (the counter x for your loop).

Then you use the computed property to run the loop x times.

Is this you want to achieve?

<template>
  <p >
    Participants:
    <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>

###

Thank to @tho-masn I could understand. And rewrite computed properties

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