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:
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.
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">
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>