Vue Conditional Rendering Practical Guide: Detailed explanation of the usage skills of v-if, v-show, v-else, v-else-if
Vue.js is An open source JavaScript framework for building interactive front-end interfaces that provides flexible conditional rendering instructions to show or hide specific elements based on different conditions. In Vue, v-if, v-show, v-else, v-else-if are one of our commonly used conditional rendering instructions. This article details the use of these directives and provides corresponding code examples.
The v-if directive is used to render specific elements based on conditions. If the condition is true, the element will be rendered, if the condition is false, the element will not be rendered.
Example 1:
Hello, World!
Sorry, the element is hidden.
In the above example, Depending on the value of the show variable, if show is true, the text in the "h1" element will be displayed, and if show is false, the text in the "p" element will be displayed.
The v-else directive is used after v-if and can be used immediately within the same label to express the opposite condition to v-if.
Example 2:
Hello, World!
Title
In the above example, When the value of show is true, the text in the "h1" element is displayed; when the value of show is false, the text in the "h3" element is displayed.
The v-show command is similar to v-if and is also used to control the display and hiding of elements under specific conditions. The difference is that v-show uses the display attribute of CSS to switch the display and hiding of elements instead of directly deleting or adding elements.
Example 3:
Hello, World!
Sorry, the element is hidden.
In the above example, When the value of show is true, the text in the "h1" element is displayed; when the value of show is false, the text in the "p" element is displayed.
The v-else-if directive is similar to the v-else directive, but it allows us to set multiple consecutive conditions. It is very useful when using v-if directive and v-else directive.
Example 4:
A+
A
B
C
F