Vue Conditional Statements
In Vue, we can use a series of directives to implement conditional rendering, which determines whether to render a block of DOM content based on the truth or falsity of specific conditions. The main directives include v-if, v-else-if, and v-else.
v-if
The v-if directive is used to conditionally render a block of content. This block is only rendered when the directive's expression returns a truthy value.
If awesome's value is false, the <h1> element will not be created or inserted into the DOM at all.
v-else
You can use the v-else directive to indicate an "else block" for v-if.
The v-else element must immediately follow an element with v-if or v-else-if, otherwise it will not be recognized.
v-else-if
v-else-if, as the name suggests, acts as an "else-if block" for v-if and can be used multiple times in a row.
Similar to v-else, v-else-if must also immediately follow a v-if or v-else-if element.
Using v-if on <template>
Because v-if is a directive, it must be added to an element. However, what if we want to toggle multiple elements? In this case, we can use a <template> element as an invisible wrapper element and use v-if on it. The final rendering result will not include the <template> element.
v-show
Another option for conditionally displaying elements is the v-show directive. Usage is roughly the same:
The difference is that elements with v-show will always be rendered and retained in the DOM. v-show simply toggles the element's CSS display property.
v-if vs v-show
-
v-ifis "true" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and rebuilt during toggling.v-ifis also lazy: if the condition is false on initial render, nothing is done—until the condition becomes true for the first time, will the conditional block start rendering. -
v-showis much simpler—regardless of the initial condition, the element is always rendered, and only the CSSdisplayproperty is toggled. -
Choice: Overall,
v-ifhas higher switching overhead, whilev-showhas higher initial rendering overhead. Therefore, if you need to toggle very frequently,v-showis better; if the condition rarely changes at runtime,v-ifis better.