How to distinguish v show from v if in vue

  • 2021-08-12 01:53:05
  • OfStack

1. v-show

Regardless of the initial conditions, the elements are always rendered and simply switched based on the attributes of CSS display: none or display: block.

2. v-if

Real rendering (real destruction and reconstruction of components) will be carried out according to the initial conditions (data's own defined data). If the conditions are true, the conditional blocks will be rendered, and if the conditions are false, the conditional blocks will not be rendered.

Note: Do not use v-if with v-for1!

When used with v-for 1, the priority of v-for is higher than that of v-if. For details, please refer to the detailed description of v-for in vue official website. Why can't it be used once? I will explain it with code below.


<ul>
 <li
 v-for = "(item, index) in list"
 v-if = "isActive"
 :key = "item.id"
 >
 {{ item.name }}
 </li>
</ul>

The above code will undergo the following operation


this.list.map( user=> {
 if (isActive) {
 return user.name
 }
})

Therefore, even if we only render a small number of elements, we have to traverse the whole list every time we re-render, regardless of isActive Whether there has been a change. If list There are a lot of data, which will cause low performance and the page may be stuck.

Summarize

Common ground:

v-if and v-show are both presented by judging the true\ false of the bound data

Differences:

v-if will render the data only when it is judged as true, and delete the included code when false. v-if will not re-judge unless the data is rendered again. It can be said that the usage tends to operate the data once.
v-show is to render the data first no matter what it is judged, but display: none on the node when false; The operation of. Therefore, without re-rendering the data, changing the value of the data can make the data show or hide.

Usage recommendation:

v-if is more suitable for operations with permissions. When rendering, judge permission data, show this function if there is one, and delete it if there is no one.
v-show is more suitable for daily use, which can reduce data rendering and unnecessary operations.
To sum up, v-if has higher switching consumption, while v-show has higher initial rendering consumption.
Therefore, v-show is better if you need to switch frequently, and v-if is better if the conditions are unlikely to change at runtime and the functional permissions are more preferred.

The above is how to distinguish v-show from v-if in vue. Please pay attention to other related articles on this site for more information about v-show and v-if!


Related articles: