What are the similarities and differences between v-show and v-if directives?


What v-show and v-if have in common

Both can control whether the element is displayed on the page,
and the usage is the same

<Model v-show="isShow" />
<Model v-if="isShow" />

And:
when the expression is true, it will occupy the position of the page;
when the expressions are all false, it will not occupy the position of the page

The difference between v-show and v-if

Different means of control

The hiding of v-show is controlled by adding css style display:none to the element, and the dom element is still there. v-if show hide is to add or delete the whole dom element

The compilation process is different

v-if switching has a partial compilation/unloading process, during which the internal event listeners and sub-components are properly destroyed and rebuilt; v-show is just a simple css-based switching

The compilation conditions are different

v-if is true conditional rendering, it will ensure that event listeners and subcomponents inside the conditional block are properly destroyed and recreated during the transition. Only when the rendering condition is false, no operation is performed until it is true before rendering

  • When v-show changes from false to true, the life cycle of the component will not be triggered
  • When v-if changes from false to true, trigger the beforeCreate, create, beforeMount, mounted hooks of the component, and trigger the beforeDestory and destroy methods of the component when it changes from true to false

performance consumption

If you want to switch a node frequently, use v-show (the switching overhead is relatively small, and the initial overhead is large). If you don't need to switch a node frequently, use v-if (initial rendering overhead is small, switching overhead is relatively large)

Usage scenarios of v-show and v-if

  • Both v-if and v-show can control the display of dom elements on the page
  • v-if is more expensive than v-show (directly operate dom node addition and deletion)
  • If you need to switch very frequently, it is better to use v-show
  • If the condition rarely changes at runtime, it is better to use v-if

Guess you like

Origin blog.csdn.net/zhaojiaxing123/article/details/129633951