I'm working in a project with vue 2. I need to know in which case the performance is better: Use v-if or v-show?. I have a long list and each item's list has a form hidden that I need show and hide to click a button that has each item list. What is better a toggle class of v-show or add and remove the form with v-if?
As a general rule for performance, v-if has higher toggle costs (whenever the conditional changes) and v-show has higher initial render costs. So if you need to toggle something frequently, use v-show. If the conditional does not change that frequently during the runtime, use v-if.
The main difference between the two is that, v-if - Only renders the element to the DOM if the expression passes. v-show - Renders all elements to the DOM and then uses the CSS display property to hide elements if the expression fails.
If v-if == true and v-show changes from true to false , the leave transition occurs as expected. If v-show== true and v-if changes from true to false , the element is immediately removed, no transition occurs. My use case for this is using both v-if and v-show around media ( img , video ).
v-if. The directive v-if is used to conditionally render a block. The block will only be rendered if the directive's expression returns a truthy value.
Assuming the question is strictly about performance:
Evan You provided a more in depth answer at VueJS Forum
v-show always compiles and renders everything - it simply adds the "display: none" style to the element. It has a higher initial load cost, but toggling is very cheap.
Incomparison, v-if is truely conditional: it is lazy, so if its initial condition is false, it won't even do anything. This can be good for initial load time. When the condition is true, v-if will then compile and render its content. Toggling a v-if block actually tearsdown everything inside it, e.g. Components inside v-if are acually destroyed and re-created when toggled, so toggling a huge v-if block can be more expensive than v-show.
Short answer:
Use v-if
if the condition won't change that often.
Use v-show
if you want to toggle the condition more often.
Note: v-show
does not remove the element from the DOM if your condition is false. So people can see it when they inspect your page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With