How to use v-if in v-for loop in vue.js 2
P粉573809727
P粉573809727 2024-01-10 17:51:13
0
1
347

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粉573809727
P粉573809727

reply all(1)
P粉511896716

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!