Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two div elements with same v-if or one wrapper?

Tags:

html

vue.js

What would you consider best practice in this situation:

<div>
   <div v-if="condition-1">Show something</div>
   <div v-if="condition-2">Show something else</div>
   <div v-if="condition-2">Show some other thing</div>
</div>

or

<div>
   <div v-if="condition-1">Show something</div>
   <div v-if="condition-2">
      <div>Show something else</div>
      <div>Show some other thing</div>
   </div>
</div>

I guess it boils down to how you value the html elements and for me, the first option is how I would prefer to write it as I find the extra div not serving a structural purpose in the second option. How would you argue for or against the two?

[Edit] As shown by the answer below, using a template element to hold the condition is the way to go

like image 567
JakobMiller Avatar asked Apr 22 '26 16:04

JakobMiller


1 Answers

In this case, I would probably use template as a wrapper for the 2 items. It makes more sense in case the 3 items are supposed to be on the same level.

https://v2.vuejs.org/v2/guide/conditional.html#Conditional-Groups-with-v-if-on-lt-template-gt

<div>
   <div v-if="condition-1">Show something</div>
   <template v-if="condition-2"> <!-- Or v-else -->
      <div>Show something else</div>
      <div>Show some other thing</div>
   </template>
</div>
like image 75
Cornel Raiu Avatar answered Apr 24 '26 08:04

Cornel Raiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!