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

Before compiling

<template  v-show="isShow">
    <div>hello</div>
</template>
Copy the code

The compiled

As can be seen from the picture, no matterisShowHow does the value of theta change,templateThe style is alwaysdisplay:none, so in usev-showWe 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

Assuming a Boolean data isShow and the DOM you want to render (

world

), 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

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

  1. V-else -if must follow the element with either v-if or V-else -if.

  2. 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!