The difference between v-if and v-show? And how to choose

Straightforward:The initialization of v-if is fast, but the switching cost is high; the initialization of v-show is slow. But the switching cost is low

a. Common points

Are dynamically displaying DOM elements

b. Difference

i: Different implementation methods

 v-if是动态的向DOM树内添加或者删除DOM元素;
 v-show是通过设置DOM元素的display样式属性控制显示或者隐藏;

ii: The compilation process is different

v-if切换有一个局部编译/卸载的过程,切换过程中合适地销毁和重建内部的事件监听和子组件;
v-show只是简单的基于css切换;

iii: Different compilation conditions

v-if是惰性的,如果初始条件为假,则什么也不做;只有在条件第一次变为真时才开始局部编译(编译被缓存?
编译被缓存后,然后再切换的时候进行局部卸载); 
v-show是在任何条件下(首次条件是否为真)都被编译,然后被缓存,而且DOM元素保留;

iiii: Different performance consumption

 v-if有更高的切换消耗;
 v-show有更高的初始渲染消耗

C. Usage scenarios

v-if is suitable for operating conditions that are unlikely to change, or changes are not very frequent.
v-show is suitable for frequent switching.

Guess you like

Origin blog.csdn.net/weixin_43131046/article/details/113862428