In Vue.js, conditional directives are used to conditionally render elements or components based on certain conditions. Here are some commonly used conditional directives in Vue.js along with examples:
v-if
The v-if directive is used to conditionally render an element or component based on the truthiness of the expression provided.
If the expression evaluates to true, the element/component is rendered; otherwise, it is removed from the DOM.
<div v-if="condition">Rendered if condition is true</div>
v-else
The v-else directive is used alongside v-if to render an element or component if the preceding v-if condition is not met.
It must be immediately following a v-if or v-else-if block and does not require any expression.
<div v-if="condition">Rendered if condition is true</div>
<div v-else>Rendered if condition is false</div>
v-else-if
The v-else-if directive is used to add additional conditions to check after a preceding v-if or v-else-if block.
It must be immediately following a v-if or another v-else-if block and requires an expression.
<div v-if="value === 'A'">Rendered if value is 'A'</div>
<div v-else-if="value === 'B'">Rendered if value is 'B'</div>
<div v-else>Rendered if value is neither 'A' nor 'B'</div>
v-show
The v-show directive is used to toggle the visibility of an element based on the truthiness of the expression provided.
Unlike v-if, the element remains in the DOM and is only hidden with CSS when the expression evaluates to false.
<div v-show="isVisible">This div is shown/hidden based on isVisible</div>
v-if with v-else
You can combine v-if and v-else to conditionally render different content based on a single condition.
<div v-if="isTrue">Rendered if isTrue is true</div>
<div v-else>Rendered if isTrue is false</div>
v-if with v-else-if with v-else
You can use v-if, v-else-if, and v-else together to conditionally render content based on multiple conditions.
<div v-if="value === 'A'">Rendered if value is 'A'</div>
<div v-else-if="value === 'B'">Rendered if value is 'B'</div>
<div v-else>Rendered if value is neither 'A' nor 'B'</div>
These conditional directives are essential for building dynamic and responsive user interfaces in Vue.js applications by selectively rendering content based on the state of the application. They provide flexibility and control over what content is displayed to the user.