v-if and v-show are two ways to conditionally render content in Vue. Both are built to conditionally render content in Vue, but in slightly different ways – which can be quite confusing. Let’s take a look at how they work, and when you would use each.
v-if vs v-show
v-if in conditional rendering is the one you will want to use most of the time. That’s because the way v-if works is to completely eliminate the DOM elements if the condition within it returns false. For example, below we’ll try to render an
tag, but only if msg is equal to 5. In the below example, msg isn’t equal to 5, so the
will never be rendered:
v-if="msg === 5">Hello World!
v-if="msg === 5">Hello World!
If we made msg reactive, and updated it, we could conditionally render the content based on a button press, like in this code:
v-if="msg.setting === true">Hello World!
This is fine for most cases. Loading one less DOM element is usually a better idea, and can help with some styling issues you may run into. If you try to look at your code in Inspect Element, you’ll see that the
tag we tried to render won’t exist if v-if is returning false. Pretty cool, right?
However, there are some situations where you’ll want the DOM element to be rendered, though, even if v-if returns false. For example, you may want to apply some Javascript to your DOM element, even if it is supposed to be hidden. For that, you can use v-show:
v-show="msg === 5">Hello World!
The difference between v-show and v-if is that v-show does not eliminate the DOM element. If the expression in v-show returns false, the element will still be rendered and exist in the document, but it will have display: none applied to it in CSS.
Other differences between v-if and v-show
There are two other key differences between v-if and v-show:
-
v-ifcan be used onelements, butv-showcannot. -
v-ifalso supportsv-elseandv-else-ifclauses, whereasv-showdoes not. Learn more about this here
Conclusion
v-if and v-show both have their uses. While v-if will stop something being rendered if the expression within it returns false, v-show will still render the element – but it will apply display: none to the element.
To learn more about Vue, you can check out my other articles here.