Vue v-show 指令
实例
根据 'showDiv' 的值,使用 v-show 指令有条件地切换 <div> 元素的可见性。
<div v-show="showDiv">This div tag can be hidden</div>
定义与用法
v-show 指令用于有条件地切换元素的可见性。
当 v-show 使用的表达式计算结果为 'false' 时,CSS 的 display 属性设置为 'none',否则 CSS display 属性将返回默认值。
带有 v-show 的元素被挂载一次并保留在 DOM 中,只有它的可见性通过 v-show 进行切换。
当与内置的 <transition> 组件一起使用时,v-show 会触发转换类和事件。
当使用 v-show 切换对象的可见性时,不会触发生命周期挂钩(如 mounted/unmounted 或 activated/deactivated)。
v-show vs. v-if
v-show 和 v-if 指令显然非常相似,因为它们都可以切换元素以使其显示或不显示,但有一些区别:
| v-show | v-if | |
|---|---|---|
| 在切换 DOM 时创建并销毁该元素? | 否 | 是 |
| 触发元素切换时 mounted/unmounted 的生命周期挂钩? | 否 | 是 |
| 当与内置的 <transition> 组件一起使用时,触发用于离开和进入的转换事件和类? | 是 | 是 |
| 是否使用内置的 <template> 元素? | 否 | 是 |
| 适用于 v-else-if 和 v-else? | 否 | 是 |
更多实例
实例
v-show 和 v-if 指令并行使用,以有条件地切换 <div> 元素的可见性。
打开实例,将条件设置为 'false',然后右键单击并检查页面,以查看带有 v-show 的元素是否仍存在于 DOM 中。
<div id="app"><div v-show="showDiv">Div tag with v-show</div><div v-if="showDiv">Div tag with v-if</div></div><script src="https://unpkg.com/vue@3/dist/vue.global.js"></script><script>const app = Vue.createApp({data() {return {showDiv: true}}})app.mount('#app')</script>
实例
一个 <p> 元素在 v-show 中变得可见,并触发 after-enter 事件。
<template><h1>JavaScript Transition Hooks</h1><p>This code hooks into "after-enter" so that after the initial animation is done, a method runs that displays a red div.</p><button @click="pVisible=true">Create p-tag!</button><br><Transition @after-enter="onAfterEnter"><p v-show="pVisible" id="p1">Hello World!</p></Transition><br><div v-show="divVisible">This appears after the "enter-active" phase of the transition.</div></template><script>export default {data() {return {pVisible: false,divVisible: false}},methods: {onAfterEnter() {this.divVisible = true;}}}</script><style scoped>.v-enter-active {animation: swirlAdded 1s;}@keyframes swirlAdded {from {opacity: 0;rotate: 0;scale: 0.1;}to {opacity: 1;rotate: 360deg;scale: 1;}}#p1, div {display: inline-block;padding: 10px;border: dashed black 1px;}#p1 {background-color: lightgreen;}div {background-color: lightcoral;}</style>