v-show vs v-if

今天要介绍的是v-show和v-if的差异

先来看一段官网的比较说明吧!

v-if is “real” conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.

v-if is also lazy: if the condition is false on initial render, it will not do anything - the conditional block won’t be rendered until the condition becomes true for the first time.

In comparison, v-show is much simpler - the element is always rendered regardless of initial condition, with CSS-based toggling.

Generally speaking, v-if has higher toggle costs while v-show has higher initial render costs. So prefer v-show if you need to toggle something very often, and prefer v-if if the condition is unlikely to change at runtime.

v-if和v-show都是让资料出现和消失,但是他们在DOM里面会有所不同
v-if它的条件如果是true的时候,资料才会在DOM显示出来,但是如果为false它的资料在DOM就不会显示出来,也就是说它会依照条件来决定是不是要把资料呈现在网页上。而v-show它是透过CSS的style来做处理的,所以它决定要不要显示只会改变display,但是它的资料其实一直都存在DOM里面,所以如果我们没有要将资料显示出来,资料会用display:none的形式保留在网页上;最後一段他有告诉我们如果需要经常切换的话使用v-show会比较适合,如果不太需时常切换的话就使用v-if会比较适合

现在用实作的范例来开启Consle看看v-show和v-if的差异吧!
https://ithelp.ithome.com.tw/upload/images/20210922/20139183n3ciB44f5Y.jpg
在v-show中它会先存放在DOM里面,由这里可以知道当我们没有按ADD ITEM的button让他开启弹跳视窗的话,他就会变成display:none,也就是他是存在着但没有被显示出来

https://ithelp.ithome.com.tw/upload/images/20210922/20139183dPBpxOo6zi.jpg
同样的呈现效果,如果我们使用的是v-if,当我们没有按ADD ITEM的button时,使用v-if指令他就不会存在DOM里面

Demo
github


<<:  Day22-生命周期

>>:  [Day7] THM Source

Day3

英文C++ How To Program中文翻的文诌诌名为"程序设计的艺术"作为...

第二次参加社群研讨会

看到标题的大家可能会感到疑惑: 为何是介绍第二次参加社群研讨会? 因为比起第一次参加社群研讨会,在这...

Day 27:Using the Elasticsearch for IaaS

这篇里所用的架构,是用Elasticsearch 2016年的版本,虽然有点过时,但这里有个新名词叫...

[访谈] APCS x 学测个申 JacobLinCool

今天邀请到一样是和我同一组铁人赛「NTNU-Unic0rn」的组员,也是师大资工同届的同学 Jaco...

资料结构和演算法

https://wolkesau.medium.com/资料结构和演算法-c3a453c9c64c ...