问题
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?
回答1:
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.
回答2:
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 with for example firebug.
回答3:
Adding that usage of 'v-if' can have unexpected consequences, since it connects and disconnects elements from the DOM instead of modifying the elements' display.
For example, if you use it on a form and end up toggling that form off using v-if, you will receive this browser console warning:
“Form submission canceled because the form is not connected”
If you use 'v-show', you won't encounter this problem.
回答4:
v-show
just only toggles display property of CSS(either "none" or "block").
When we use v-show
the HTML DOM will be on the page only(with the "display" property).
But where as if we use v-if
it removes the entire DOM from the page or recreates the entire DOM based on the condition.
Check this example.
<p v-if="ok">If Check</p>
<p v-show="ok">Show Check</p> //try to set "ok" by true and false and inspect HTML
回答5:
V-show
It will load/render all the element in the DOM at once and if the value is false v-show="false" then it will set the element's display to "none"
V-if
It will not load/render the element until the condition is met and renders element as condition is met
回答6:
v-if: add or remove your element.
v-show: change visible css attibute.
if toggle often, v-show is better. otherwise, we use v-if(since css cost initial load time).
来源:https://stackoverflow.com/questions/42419192/what-is-better-in-vue-js-2-use-v-if-or-v-show