This is the third day of my participation in the August Text Challenge.More challenges in August
In this article, we will talk about how to use v-show and V-if, V-else, v-else, what to pay attention to when using them, and what are the differences between them.
v-show
The use of the v – show
V-show simply toggles the element’s CSS property display.
Given a Boolean value isShow=true, we can use it as follows:
<h1 v-show="isShow">hello</h1>
Copy the code
It essentially changes the display value of h1 as follows:
document.querySelector("h1").style.display="none"
Copy the code
Of course, you can use any method you like to get the element, so here we use querySelector to get h1. When using v-show, we need to note that v-show does not support the
element. If you use it on the
element, the following happens:
Before compiling
<template v-show="isShow">
<div>hello</div>
</template>
Copy the code
The compiled
As can be seen from the picture, no matterisShow
How does the value of theta change,template
The style is alwaysdisplay:none
, so in usev-show
We need to pay attention to this.
V-if, V-else -if, V-else
V-if, v-else, v-else
Conditionally render elements based on the true or false value of the expression. The element and its data binding/component are destroyed and rebuilt during the switch. If the element is
, its contents are extracted as a conditional block.
Assuming a Boolean data isShow and the DOM you want to render (
), if isShow=ture, the DOM structure has this line of code; If isShow=false, this line of code does not exist in the DOM structure.
What if we want to switch between multiple elements? At this point, we need to wrap it with the
element and use v-if on it. Let’s see what happens to them.
Before compiling
<template v-if="isShow">
<div>hello</div>
<div>world</div>
</template>
Copy the code
After compiling, isShow=true displays the contents of the template
<div>hello</div>
<div>world</div>
Copy the code
After compiling, isShow=false and do not display the DOM
<! --v-if-->
Copy the code
Precautions for V-else -if and V-ELSE
-
V-else -if must follow the element with either v-if or V-else -if.
-
The V-else element must be immediately followed by an element with v-if or v-else-if, otherwise it will not be recognized.
conclusion
Officially, V-if has a higher switching overhead, while V-show has a higher initial rendering overhead. Therefore, v-show is good if you need to switch very frequently; It is better to use V-if if conditions rarely change at run time.
For the above statement, it is good that we abide by it, but in actual development, we also need to use it according to functional needs, which needs to be defined by ourselves.
For more articles, the portal has opened: Look back at the Vue3 catalogue!