vue 实现div切换效果
Vue 实现 div 切换效果
在 Vue 中实现 div 切换效果可以通过多种方式完成,常见的方法包括使用 v-if、v-show、动态组件或结合 CSS 过渡动画。以下是几种实现方案:
使用 v-if 或 v-show 切换
v-if 和 v-show 是 Vue 内置指令,适合简单的显隐切换。v-if 会销毁和重建 DOM 元素,而 v-show 仅通过 CSS 的 display 属性控制显隐。

<template>
<div>
<button @click="toggleDiv">切换 Div</button>
<div v-if="isVisible">内容 1</div>
<div v-else>内容 2</div>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
};
},
methods: {
toggleDiv() {
this.isVisible = !this.isVisible;
}
}
};
</script>
结合 CSS 过渡动画
通过 Vue 的 <transition> 组件可以为切换效果添加动画,提升用户体验。
<template>
<div>
<button @click="toggleDiv">切换动画效果</button>
<transition name="fade">
<div v-if="isVisible" class="box">带动画的内容</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
};
},
methods: {
toggleDiv() {
this.isVisible = !this.isVisible;
}
}
};
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.box {
padding: 20px;
background: #eee;
}
</style>
动态组件切换
如果需要切换多个组件,可以使用 Vue 的 <component> 动态组件,配合 is 属性实现灵活切换。

<template>
<div>
<button @click="currentComponent = 'ComponentA'">显示 A</button>
<button @click="currentComponent = 'ComponentB'">显示 B</button>
<component :is="currentComponent"></component>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
components: { ComponentA, ComponentB },
data() {
return {
currentComponent: 'ComponentA'
};
}
};
</script>
使用 Vue Router 实现路由切换
对于页面级切换,可以通过 Vue Router 的路由系统实现不同视图的切换。
// router.js
import { createRouter, createWebHistory } from 'vue-router';
import Page1 from './views/Page1.vue';
import Page2 from './views/Page2.vue';
const routes = [
{ path: '/page1', component: Page1 },
{ path: '/page2', component: Page2 }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
在模板中通过 <router-view> 显示当前路由对应的组件:
<template>
<div>
<router-link to="/page1">Page 1</router-link>
<router-link to="/page2">Page 2</router-link>
<router-view></router-view>
</div>
</template>
以上方法可根据实际需求选择,简单显隐用 v-if/v-show,复杂动画用 <transition>,多组件切换用动态组件,页面级切换用 Vue Router。






