How to increase the number of icons based on data in Vue
P粉832490510
P粉832490510 2024-01-10 17:03:43
0
2
422

I sent an API request and got a different number of participants (from 1 to 5). Based on this number, a corresponding number of icons should be displayed in the modal box. If there are 3 participants, there should be 3 user icons in the modal. I know how to do it in React, but I'm starting to learn Vue3 and don't know how to do it.

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

In React, I would write like this. But how to rewrite it in Vue? Let’s be clear, where should it be placed?

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粉832490510
P粉832490510

reply all(2)
P粉647449444

Thanks to @tho-masn's help, I was able to understand and rewrite the computed properties

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

First, you need to create a calculated property that returns the number of participants (the loop's counter x).

You then run the loop using the computed property x times.

Is this what you want to achieve?

<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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template