我發(fā)送了一個(gè)API請(qǐng)求並獲得了不同數(shù)量的參與者(從1到5)。根據(jù)這個(gè)數(shù)量,在模態(tài)框中應(yīng)該會(huì)顯示對(duì)應(yīng)數(shù)量的圖示。如果有3個(gè)參與者,則模態(tài)框中應(yīng)該有3個(gè)使用者圖示。 我知道如何在React中實(shí)現(xiàn),但我開始學(xué)習(xí)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中,我會(huì)這樣寫。但在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; });
感謝 @tho-masn 的幫助,我能夠理解並重新編寫計(jì)算屬性
numberOfParticipants () { let participants = 1 for(let i=1; i < this.randomActivity.participants; i++) { participants += 1; } return participants }
首先,您需要建立一個(gè)計(jì)算屬性,該屬性傳回參與者的數(shù)量(循環(huán)的計(jì)數(shù)器 x
)。
然後,您使用該計(jì)算屬性執(zhí)行循環(huán) x
次。
這是您想要實(shí)現(xiàn)的嗎?
<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>