【问题标题】:How to increase the number of icons according the fetched data in vuevue中如何根据获取的数据增加图标的数量
【发布时间】:2021-11-09 13:26:24
【问题描述】:

我发送 Api 请求并获得不同数量的参与者(从 1 到 5)。根据这个数字,图标的数量应该出现在模态框上。如果有 3 个参与者,模态中应该有 3 个用户图标。 我知道如何在 React 中做到这一点,但是我开始研究 Vue3 并且不知道。

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

在 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;
  });

【问题讨论】:

    标签: vue.js icons array.prototype.map


    【解决方案1】:

    感谢@tho-masn 我能理解。并重写计算属性

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

    【讨论】:

      【解决方案2】:

      首先,您创建一个计算属性,该属性返回参与者的数量(循环的计数器 x)。

      然后使用计算属性运行循环x 次。

      这是你想要实现的吗?

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

      【讨论】:

        猜你喜欢
        • 2021-11-02
        • 1970-01-01
        • 2021-11-24
        • 1970-01-01
        • 2020-02-24
        • 2019-10-07
        • 2013-03-18
        • 2021-05-16
        • 1970-01-01
        相关资源
        最近更新 更多