vue 实现vshow
Vue 实现 v-show 指令
Vue 的 v-show 指令通过控制元素的 display CSS 属性来实现显示和隐藏。与 v-if 不同,v-show 不会移除 DOM 元素,而是通过样式切换。

基本用法
<template>
<div>
<button @click="toggleVisibility">Toggle Visibility</button>
<div v-show="isVisible">This element is visible</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
};
},
methods: {
toggleVisibility() {
this.isVisible = !this.isVisible;
}
}
};
</script>
实现原理
v-show 的核心逻辑是根据表达式的值动态设置元素的 display 样式:
- 当表达式为
true时,元素显示(display设置为原始值,如block、inline等)。 - 当表达式为
false时,元素隐藏(display: none)。
自定义 v-show
可以通过自定义指令实现类似 v-show 的功能:
<template>
<div v-custom-show="isVisible">Custom v-show</div>
</template>
<script>
export default {
directives: {
'custom-show': {
bind(el, binding) {
el.style.display = binding.value ? '' : 'none';
},
update(el, binding) {
el.style.display = binding.value ? '' : 'none';
}
}
},
data() {
return {
isVisible: true
};
}
};
</script>
与 v-if 的区别
v-show:仅切换display样式,DOM 元素始终保留。适合频繁切换的场景。v-if:条件为false时会销毁 DOM 元素,条件为true时重新创建。适合不频繁切换的场景。
性能考虑
- 频繁切换显示状态时,
v-show性能更好,因为避免了 DOM 的频繁销毁和重建。 - 初始渲染成本较高时,
v-if更高效,因为可以跳过不必要的 DOM 渲染。







