Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better in vue.js 2, use v-if or v-show?

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?

like image 408
Jedidias Avatar asked Feb 23 '17 14:02

Jedidias


People also ask

Which is better V-show or 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.

What is difference between V-if and V-show?

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.

Can we use V-if and V-show together?

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 ).

What does V-if do in Vue?

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.


2 Answers

tl;dr

Assuming the question is strictly about performance:

  • v-show: expensive initial load, cheap toggling,
  • v-if: cheap initial load, expensive toggling.

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.

like image 119
bypatryk Avatar answered Oct 04 '22 19:10

bypatryk


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.

like image 20
Ron van Asseldonk Avatar answered Oct 04 '22 20:10

Ron van Asseldonk