Difference between v-if and v-show in Vue.js
April 8, 2022 ‐ 2 min read
To manipulate your Vue template you use Vue directives; special HTML attributes which are processed by Vue. Now in order to conditionally show or hide parts of your template there are two options which function similarly at first glance:
v-show. Functionally they work practically the same, however the difference between the
v-show directives is behind the scenes.
The difference between the two is in how the hidden parts of your template are rendered. Which ultimately determines which directive you should use in a certain use-case.
They differ as follows:
v-if completely removes the part of your template to conditionally hide from your final HTML code. Once the condition evaluates to true, Vue adds the part of your template that should be conditionally shown to your HTML code.
v-show on the other hand will always add the part that is conditionally hidden to your DOM. Based on the passed condition the CSS styling
display: none; is added to the element. Once the condition evaluates to true the CSS styling is removed from the element.
Therefore the weigh-off is often in how you expect the conditional part of your template to change during the time it is mounted. For
v-show there is a penalty in the initial rendering time. Vue will always render the conditional part of your template, even if it is directly hidden using CSS. For
v-if you pay the price whenever the condition changes, in such a case Vue removes or adds HTML to your DOM which is more expensive than toggling a CSS property.
So in short; if you expect the condition to change (often) while the component is mounted use
v-show. If you either show or hide parts of your template based on a (fairly) static props value for example use