Vue: the difference between V-IF and v-show

Little Rooster Kawaii~ 2022-05-14 14:19:21 阅读数:271


The following code , Use v-show, Only when the goals When there are elements in the array , To display the list

 data() {

return {
 goals: [], goal: "" };
<ul v-show = "goals.length > 0">
<li v-for="g in goals" key="g">{

If you use dev tool see , Will see , Even if goals Array is empty , The list also exists in DOM in , Just now css style Is set to hide :

<ul style="display: none;"></ul>

therefore ,v-show Just use css Hide or show items .v-show=false It's equivalent to setting : style=“display: none;” conversely :v-show=true when There is no such thing

<ul style="">...</ul>

By contrast ,v-if Really from DOM Delete or add elements to .

How to choose v-if or v-show: One side , Use css Showing or hiding means that you don't have to add and remove elements all the time , Adding and removing elements will reduce performance , Therefore use v-show Can improve performance . But on the other hand , It also means that DOM There are several elements that are not needed at present , This is not particularly ideal .

therefore , Based on experience , Usually only v-if , Only if there is an element whose visibility state changes frequently will you fall back to using v-show.

In short ,v-if Add or remove elements ,v-show Hide or show existing elements .

版权声明:本文为[Little Rooster Kawaii~]所创,转载请带上原文链接,感谢。