Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

501
Visualizações
Vue3js: how to loop over array exacly 5 times and conditionaly check elements inside?

please note, that I spend the last 2h searching through SO's similar subjects, to get to a solution, but failed. That's why I ask you now for help.

I am trying to achieve the following:

I have a scoreboard with some results, which should look like this:

  • John Doe 100 pts
  • John Smith 50 pts
  • No Name
  • No Name
  • No Name

I have an array for this called scoreBoardArray.

data() {
  return {
     scoreBoardArray: [
        { id: '1', name: 'John Doe', pts: 100 },
        { id: '2', name: 'John Smith', pts: 50 },
     ],
   }
},

I can loop through it, but fail to do it exactly 5 times and spit out the "No Name", when no record is found.

My code (and my attempts to solve the problem):

<ul>
   <li v-for="item in scoreBoardArray" :key="item.id">
      <span v-if="item.id">{{ item.name }} {{ item.pts }}</span>
      <span v-if="!item.id">No Name</span
   </li>
</ul>

of course, I have tried to solve the problem with the use of a computed property and a simple for(let i=0; i<6; i++) {...} loop but somehow cannot get it working.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Sure, this is something you could achieve with a computed property.

Try just adding some empty objects to the end of your array to pad it out to 5 values.

computed: {
  scoreboard() {
    let append = []
    const appendCount = 5 - this.scoreBoardArray
    for (let i = 0; i < appendCount; i++) {
      append[i] = {}
    }
    return [...this.scoreBoardArray, ...append]
  }
}

But since these objects are empty you'll encounter problems with your v-for loop keys. To fix it you could use indices as keys:

<li v-for="(item, index) in scoreboard" :key="index">
about 4 years ago · Juan Pablo Isaza Relatório

0

You could use a computed property to slice the first 5 elements in scoreBoardArray[] and to get the number of "No Name" dummy items needed (named topScores and dummyLength, respectively):

export default {
  computed: {
    topScores() {
      return this.scoreBoardArray
        .slice()                      // create a copy
        .sort((a,b) => b.pts - a.pts) // sort by points
        .slice(0, 5)                  // first 5
    },
    dummyLength() {
      return Math.max(0, 5 - this.topScores.length)
    }
  }
}

And update the template to render the computed props in a v-for, rendering the topScores items and then dummyLength dummy items:

<ul>
  <li v-for="item in topScores" :key="item.id">
    <span>{{ item.name }} ({{ item.pts }})</span>
  </li>
  <li v-for="n in dummyLength">No Name</li>
</ul>

demo

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda