susanBuck / e28-spring20

0 stars 0 forks source link

v-if within a v-for #37

Closed susanBuck closed 4 years ago

susanBuck commented 4 years ago

I had a good question come in via email from a student and wanted to share the answer here in case other students faced a similar question.

In the question, the student had an array of winners:

winners: ['Computer', 'Computer', 'Player', 'Tie', 'Tie']

And they wanted to loop through those winners displaying different content based on whether the winner was Computer, Player, or Tie.

This could be accomplished doing something like this:

<ul>
    <li v-for='winner in winners'>
        <span v-if='winner == "Computer"'>
            Computer won
        </span>
        <span v-else-if='winner == "Player"'>
            Player won
        </span>
        <span v-else>
            It was a tie
        </span>
    </li>
</ul>

The question is whether this is okay or not - because when we learned about conditional rendering, I discussed how you should not combine v-if and v-for directives for performance reasons.

However, that only applies when you're applying v-if and v-for on the same element. In the above example, v-if is used on elements nested within the v-for, so it's okay.

Ref: