search

Home  >  Q&A  >  body text

How to use v-if in v-for loop in vue.js 2

I have this code setup

<div v-for="person in persons">
    <div v-if="person.status == 'public'" :key="person.id">
        Hi,my name is {{person.name}}
    </div>
    <div v-else :key="person.id">
        This person is private
    </div>
</div>
All values ​​of the

status attribute in the person object are "public"!

But in the above code snippet, it is not the if block that continues to run, but the else block.

If I rewrite the code like this:

<div v-for="person in persons" :key="person.id">
    <div v-if="person.status == 'public'">
        Hi,my name is {{person.name}}
    </div>
    <div v-else>
        This person is private
    </div>
</div>

Then it will work normally.

What's wrong with the first clip?

Looks like the "key" attribute plays a role in this. Is the way I'm using it wrong? Why does it affect the output?

Which of these is the most correct way to write an "if" statement inside a "for" loop?

I've been using the first method in other loops in my code before and it never had a problem until today. Do I need to update them all to be similar to the second method to avoid weird behavior like this?

P粉573809727P粉573809727329 days ago389

reply all(1)I'll reply

  • P粉511896716

    P粉5118967162024-01-11 11:09:43

    From vue v-for and v-if

    You are using v-for and v-if correctly. The problem is that :key is placed on the conditional block.

    Either way, something will be rendered in the div, you have two possible outcomes, and the key should be on the v-for line. You should not conditionally render the :key attribute.

    // 1
    <div>
       <div>
          Hi,my name is john
       </div>
    </div>
    
    // 2
    <div>
      <div>
         This person is private
      </div>
    </div>
    

    reply
    0
  • Cancelreply