Vue v-show
Discover how to use v-show to make an element visible or invisible.
Because the condition is directly expressed in the HTML tag attribute, v-show is simple to employ.
Conditional Visibility
The v-show directive sets the CSS ‘display’ property value to ‘none’ in order to conceal an element when the condition is ‘false’.
Once v-show has been written as an HTML attribute, we need to include a condition to determine whether or not the element is visible.
Syntax
This div tag can be hidden
The boolean Vue data property “showDiv” in the code above has a value of either “true” or “false.” If ‘showDiv’ is ‘true’ the div tag is shown, and if it is ‘false’ the tag is not shown.
Example
Only when the showDiv property is set to ‘true’ will the <div> element be displayed.
This div tag can be hidden
v-show vs. v-if
The difference between v-show and v-if is that v-if creates (renders) the element depending on the condition, but with v-show the element is already created, v-show only changes its visibility.
Consequently, it is preferable to utilize v-show to change an object’s visibility since it is simpler for the browser to handle, can result in a quicker response, and enhances user experience.
Because v-if can be used with v-else-if and v-else, it is preferred over v-show.
Using the same Vue property, v-show and v-if are applied independently to two distinct <div> elements in the example below. If you open the sample and look at the code, you’ll see that v-if truly eliminates the <div> element whereas v-show simply modifies the CSS display value to ‘none’.
Example
Only when the showDiv property is set to ‘true’ will the two <div> elements be displayed. The <div> element with v-if is destroyed when the showDiv property is set to ‘false,’ while the <div> element with v-show just has the CSS display property set to ‘none.’ This can be observed when we use the browser to check the example page.
Div tag with v-show
Div tag with v-if