v-if 和 v-show的比较

v-if指令
根据表达式的值动态地插入或者移除DOM元素
<!DOCTYPE html>
<html>
<head>
<script src="js/vue.js"></script>
</head>
<body class="native">
<div id="example">
<p v-if="greet1">
<template>
<p>Directive1</p>
</template>
</p>
<p v-if="greet2">
<template>
<p>Directive2</p>
</template>
</p>
</div>
</body>
<script type="text/javascript">
new Vue({
el: '#example',
data: {
greet1: true,
greet2: false,
}
});
</script>
</html>
最后在DOM树中,显示如下:
<body class="native">
<div id="example">
<p>
<p>Directive1</p>
</p>
</div>
</body>
可以看出符合条件的template在DOM树中显示了出来,
不符合条件的template没有出现在DOM树中。


v-show指令
根据表达式的值来显示或者隐藏DOM元素


<!DOCTYPE html>
<html>
<head>
<script src="js/vue.js"></script>
</head>
<body class="native">
<div id="example">
<p v-show="greet1">
<template>
<p>Directive1</p>
</template>
</p>
<p v-show="greet2">
<template>
<p>Directive2</p>
</template>
</p>
</div>
</body>
<script type="text/javascript">
new Vue({
el: '#example',
data: {
greet1: true,
greet2: false,
}
});
</script>
</html>


在chrome的element中显示如下:


<body class="native">
<div id="example">
<p>
<p>Directive1</p>
</p>
<p style="display: none;">
<p>Directive2</p>
</p>
</div>
</body>
可以看到在DOM树中Directive1和Directive2都存在,
但是Directive2不显示而已。我们可以看到style="display: none;"
样式的存在。


从用户的角度来看,v-if和v-show没有区别,因为用户不关心底层的实现原理。
但是作为开发人员必须知道v-if和v-show的区别,在什么情景下适合使用v-if,
在什么场景下适合使用v-show。
v-if是真实的渲染,v-show则是通过CSS样式的简单切换来实现dom元素的显示和隐藏。
如果频繁地进行模块的切换,显然使用v-if是不合适的,因为每一次都会卸载或者编译,
这种切换消耗是比较高的。此时,采用v-show更为合适。v-show模块只卸载或者编译一次。
它的切换仅仅只是通过CSS实现,切换消耗主要是渲染消耗。

猜你喜欢

转载自blog.csdn.net/qq_23143555/article/details/80713268