vue 实现div切换效果
使用 Vue 实现 Div 切换效果
方法一:通过 v-if 和 v-else 切换
通过 Vue 的指令 v-if 和 v-else 实现两个 div 的切换显示。
<template>
<div>
<button @click="toggleDiv">切换 Div</button>
<div v-if="showDiv1">这是第一个 Div</div>
<div v-else>这是第二个 Div</div>
</div>
</template>
<script>
export default {
data() {
return {
showDiv1: true
};
},
methods: {
toggleDiv() {
this.showDiv1 = !this.showDiv1;
}
}
};
</script>
方法二:通过 v-show 切换
v-show 通过 CSS 的 display 属性控制显示和隐藏,适合频繁切换的场景。

<template>
<div>
<button @click="toggleDiv">切换 Div</button>
<div v-show="showDiv1">这是第一个 Div</div>
<div v-show="!showDiv1">这是第二个 Div</div>
</div>
</template>
<script>
export default {
data() {
return {
showDiv1: true
};
},
methods: {
toggleDiv() {
this.showDiv1 = !this.showDiv1;
}
}
};
</script>
方法三:动态组件切换
通过 Vue 的 <component> 动态组件实现多个 div 的切换。

<template>
<div>
<button @click="currentComponent = 'Div1'">显示 Div1</button>
<button @click="currentComponent = 'Div2'">显示 Div2</button>
<component :is="currentComponent"></component>
</div>
</template>
<script>
export default {
data() {
return {
currentComponent: 'Div1'
};
},
components: {
Div1: {
template: '<div>这是第一个 Div</div>'
},
Div2: {
template: '<div>这是第二个 Div</div>'
}
}
};
</script>
方法四:通过 CSS 过渡效果增强切换
结合 Vue 的 <transition> 组件实现平滑的过渡效果。
<template>
<div>
<button @click="showDiv1 = !showDiv1">切换 Div</button>
<transition name="fade">
<div v-if="showDiv1" key="div1">这是第一个 Div</div>
<div v-else key="div2">这是第二个 Div</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
showDiv1: true
};
}
};
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
方法五:多内容切换(多个 div 切换)
通过数组和索引控制多个 div 的切换。
<template>
<div>
<button @click="nextDiv">下一个 Div</button>
<div v-for="(content, index) in contents" :key="index" v-show="currentIndex === index">
{{ content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
contents: ['Div 1 内容', 'Div 2 内容', 'Div 3 内容'],
currentIndex: 0
};
},
methods: {
nextDiv() {
this.currentIndex = (this.currentIndex + 1) % this.contents.length;
}
}
};
</script>
以上方法可以根据实际需求选择,v-if 适合条件渲染,v-show 适合频繁切换,动态组件适合复杂组件切换,过渡效果适合需要动画的场景。






