Detailed explanation: the difference between v-if and v-show of vue

The most complete analysis of the difference between v-if and v-show in the vue project

Sometimes it is necessary to control "conditional rendering" in the vue project, and most of the time it is controlled by v-if or v-show. I think many people know the difference between the two, but recently I found that there are many projects in the project team Comrades can't figure it out, almost all use it indiscriminately, and if something goes wrong, they still can't figure out where the problem is. Now let’s briefly talk about the difference between these two things.

1. Functional difference

Both can control display and hide, but there are huge differences in essence:

1.1 v-show
   v-show严格意义上说“条件隐藏”。浏览器首先不管三七二十一, 把HTML元素先渲染起来,符合条件就显示,不符合条件display就为none,不显示,但是元素还在那。。
1.2 v-if
   v-if是真正意义上的“条件渲染”。浏览器先判断符不符合条件,符合了再渲染, 否则不渲染DOM,浏览器中找不到这个DOM

Second, the difference between the vue life cycle

 v-if由于是重新渲染,所以每次切换一次会重新走一次生命周期,v-show由于只是控制显示隐藏,
    所以除了初始化渲染,其他时候都不会再走相关生命周期了。

3. Performance difference

1、v-if有更高的切换开销,v-show有更高的初始渲染开销。如果需要频繁的切换,使用v-show比较好,如果运行条件很少改变,使用v-if比较好。

2、v-show比v-if性能更高,因为v-show只能动态的改变样式,不需要增删DOM元素。所以当程序不是很大时候,v-if和v-show区别都不大,如果项目很大,推荐多用v-show,较少浏览器后期操作的性能。

3、需要多种条件场景,比如id=1=2=3.....时候,因为只有v-if,可以和v-else等连用,这种比较适合用v-if

4、v-show不支持<template>语法

5、v-if切换时候回实时的销毁和重建内部的事件、钩子函数等,v-show只会初始化渲染时候执行,再切换时候不会执行生命后期的过程

If it is helpful to you, remember to like and follow, thank you!

Guess you like

Origin blog.csdn.net/weixin_45449504/article/details/109486972