vue 中 v-if 和 v-show 的区别是什么
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 90
Author 回答者: zhaofeihao
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.
v-show 总是会进行编译和渲染的工作 - 它只是简单的在元素上添加了 display: none;
的样式。v-show 具有较高的初始化性能成本上的消耗,但是使得转换状态变得很容易。
相比之下,v-if 才是真正「有条件」的:它的加载是惰性的,因此,若它的初始条件是 false,它就不会做任何事情。这对于初始加载时间来说是有益的,当条件为 true 时,v-if 才会编译并渲染其内容。切换 v-if 下的块儿内容实际上时销毁了其内部的所有元素,比如说处于v-if下的组件实际上在切换状态时会被销毁并重新生成,因此,切换一个较大v-if块儿时会比v-show消耗的性能多。