Vue3 Conditional Statements
In Vue 3, you can use multiple conditional statements in templates to control component rendering.
The main conditional statements are:v-if、v-else-if、v-elseandv-show, the following are their usage and differences:
v-if: the element, when the condition isfalsewill not be rendered to the DOM, suitable for situations where conditions change infrequently.v-show: the element is always rendered to the DOM, suitable for situations where conditions change frequently, with better performance when toggling visibility.v-else-ifandv-else: used to handle multiple conditional branches, combined withv-ifuse.
Conditional Judgment
v-if
Conditionally renders elements based on the truthiness of an expression. If the expression is true, the element is rendered; if false, it is not rendered (the element will not be created in the DOM).
The conditional judgment uses the v-if directive. The element is displayed only when the directive's expression returns true:
v-if Directive
Use the v-if directive on an element:
Try it »
Here, the v-if directive will decide whether to insert the p element based on the value (true or false) of the expression seen.
Because v-if is a directive, it must be added to a single element. If there are multiple elements, you can wrap them in a <template> element and use v-if on it. The final rendered result will not include the <template> element.
v-if Directive
Use the v-if directive on a <template> element:
Try it »
v-else
Used together with v-if, it renders the element when the preceding v-if expression is false.
You can use the v-else directive to add an "else" block to v-if:
v-else Directive
Generate a random number, determine whether it is greater than 0.5, and then output the corresponding information:
Try it »
v-else-if
To add additional conditional checks between v-if and v-else, you can use multiple v-else-if directives in succession.
v-else Directive
Check the value of the type variable:
Try it »
v-else and v-else-if must follow v-if or v-else-if.
v-show
Conditionally shows or hides an element based on the truthiness of an expression. Unlike v-if, v-show always keeps the element in the DOM and only controls the element's visibility through the CSS display property.
We can also use the v-show directive to display elements based on conditions:
If you need to frequently toggle the visibility of an element, v-show is recommended, because it simply toggles CSS styles rather than re-rendering the entire element.
Other Extensions