vue实现div切换
Vue 实现 div 切换的方法
使用 v-if 和 v-else
通过 Vue 的指令 v-if 和 v-else 可以动态切换 div 的显示与隐藏。这种方式会完全销毁和重建 DOM 元素。
<template>
<div>
<button @click="toggleDiv">切换 Div</button>
<div v-if="showDiv">这是第一个 Div</div>
<div v-else>这是第二个 Div</div>
</div>
</template>
<script>
export default {
data() {
return {
showDiv: true
};
},
methods: {
toggleDiv() {
this.showDiv = !this.showDiv;
}
}
};
</script>
使用 v-show
v-show 通过 CSS 的 display 属性控制元素的显示与隐藏,适用于频繁切换的场景,性能较好。

<template>
<div>
<button @click="toggleDiv">切换 Div</button>
<div v-show="showDiv">这是第一个 Div</div>
<div v-show="!showDiv">这是第二个 Div</div>
</div>
</template>
<script>
export default {
data() {
return {
showDiv: true
};
},
methods: {
toggleDiv() {
this.showDiv = !this.showDiv;
}
}
};
</script>
使用动态组件
通过动态组件 <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>
使用 CSS 过渡效果
结合 Vue 的 <transition> 组件可以为切换添加动画效果。
<template>
<div>
<button @click="showDiv = !showDiv">切换 Div</button>
<transition name="fade">
<div v-if="showDiv">这是带有过渡效果的 Div</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
showDiv: true
};
}
};
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
使用路由切换
如果需要通过路由切换不同的 div 内容,可以使用 Vue Router 的 <router-view>。
<template>
<div>
<router-link to="/div1">Div 1</router-link>
<router-link to="/div2">Div 2</router-link>
<router-view></router-view>
</div>
</template>
总结
v-if和v-else适合条件渲染,切换时会销毁和重建 DOM。v-show适合频繁切换,通过 CSS 控制显示与隐藏。- 动态组件适合切换不同的组件。
<transition>可以为切换添加动画效果。- 路由切换适合通过 URL 控制内容显示。






