Skip to content

Instantly share code, notes, and snippets.

@joshsarna
Last active April 9, 2019 03:55
Show Gist options
  • Save joshsarna/527ee5c33438ec725bb1ae3f1351068b to your computer and use it in GitHub Desktop.
Save joshsarna/527ee5c33438ec725bb1ae3f1351068b to your computer and use it in GitHub Desktop.

VueJS offers two ways to display information conditionally with directives: v-if and v-show. v-if will only render to the DOM when its value evaluates to true. v-show will render to the DOM either way but will have inline styling to the effect of display: none; if its value evaluates to false.

v-if

<div class="root">
  <p v-if="true">Hello</p>
</div>

renders to the DOM:

<div class="root">
  <p>Hello</p>
</div>

Whereas

<div class="root">
  <p v-if="false">Hello</p>
</div>

renders to the DOM:

<div class="root">
</div>

v-else

Briefly:

<div class="root">
  <p v-if="false">This will render if the value of v-if evaluates to true</p>
  <p v-else-if="true">This will render if the value of the v-else-if evaluates to true and the value of the most recent v-if evaluates to false</p>
  <p v-else>This will render if the value of the most recent v-if (and those of all following v-else-ifs) evaluates to false</p>
</div>

renders to the DOM:

<div class="root">
  <p>This will render if the value of the v-else-if evaluates to true and the value of the most recent v-if evaluates to false</p>
</div>

v-show

<div class="root">
  <p v-show="true">Hello</p>
</div>

renders to the DOM:

<div class="root">
  <p>Hello</p>
</div>

Whereas

<div class="root">
  <p v-show="false">Hello</p>
</div>

renders to the DOM:

<div class="root">
  <p style="display: none;">Hello</p>
</div>

Comparison

v-show is useful if you want to manipulate an html element while it's not shown (you can't do that with v-if), but it doesn't give you access to v-else, and having more DOM elements affects performance, so usually v-if is better.

v-show technically is also a form of in-line styling, which is a dangerous road to start down.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment