v-if
和 v-show
是 Vue.js 中常用的条件渲染指令,它们的作用是根据条件来控制元素的显示与隐藏。
格式也差不多:
<div v-show="isShow" />
<div v-if="isShow" />
当 isShow 为 true 时显示当前元素,为 false 时隐藏
虽然它们的效果类似,但是它们在实现原理和使用场景上有一些区别。
1. 实现原理:
-
v-if
:根据条件动态添加或移除元素及其子组件。当条件为false
时,元素不会渲染到 DOM 中。每次条件切换,都会触发组件的销毁和重新创建。
v-if
在 Vue 中是如何实现的:
export const transformIf = createStructuralDirectiveTransform(
/^(if|else|else-if)$/,
(node, dir, context) => {
return processIf(node, dir, context, (ifNode, branch, isRoot) => {
// ...
return () => {
if (isRoot) {
ifNode.codegenNode = createCodegenNodeForBranch(
branch,
key,
context
) as IfConditionalExpression
} else {
// attach this branch's codegen node to the v-if root.
const parentCondition = getParentCondition(ifNode.codegenNode!)
parentCondition.alternate = createCodegenNodeForBranch(
branch,
key + ifNode.branches.length - 1,
context
)
}
}
})
}
)
-
v-show
:通过 CSS 的display
属性来控制元素的显示和隐藏。当条件为false
时,元素的display
属性被设置为none
,元素仍然存在于 DOM 中。
v-show
在 Vue 中是如何实现的:文章来源:https://www.toymoban.com/news/detail-571703.html
export const vShow: ObjectDirective<VShowElement> = {
beforeMount(el, { value }, { transition }) {
el._vod = el.style.display === 'none' ? '' : el.style.display
if (transition && value) {
transition.beforeEnter(el)
} else {
setDisplay(el, value)
}
},
mounted(el, { value }, { transition }) {
if (transition && value) {
transition.enter(el)
}
},
updated(el, { value, oldValue }, { transition }) {
// ...
},
beforeUnmount(el, { value }) {
setDisplay(el, value)
},
}
2. 初始渲染开销:
-
v-if
:在初始渲染时,如果条件为false
,则元素不会被渲染到 DOM 中,减少了初始渲染的开销。但是在条件切换时,会有销毁和重新创建的开销。 -
v-show
:在初始渲染时,无论条件为true
还是false
,元素都会被渲染到 DOM 中。因此初始渲染的开销比v-if
稍微大一些。但在条件切换时,不需要销毁和重新创建元素,因此开销比v-if
小。
3. 频繁切换的性能:
-
v-if
:适合在条件很少改变的情况下使用,因为条件切换时需要销毁和重新创建组件,开销较大。 -
v-show
:适合在条件需要频繁切换的情况下使用,因为切换时只是通过修改 CSS 的display
属性来控制元素的显隐,开销较小。
4. CSS 设计影响:
-
v-if
:在条件为false
时,元素及其子组件都不会存在于 DOM 中,不会占据空间。可以很方便地在 CSS 中使用v-if
控制不同的布局。 -
v-show
:在条件为false
时,元素的display
属性被设置为none
,元素仍然存在于 DOM 中,会占据空间。在 CSS 中不能使用v-show
控制布局,因为元素始终存在于 DOM 中。
综上所述,v-if
适合在条件切换较少的情况下使用,可以在初始渲染时减少开销。v-show
适合在条件需要频繁切换的情况下使用,开销较小。选择使用哪个指令取决于具体的需求和场景。文章来源地址https://www.toymoban.com/news/detail-571703.html
到了这里,关于Vue 中 v-if 和 v-show 的区别的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!