vue实现点击切换内容
使用 v-if/v-else 指令切换内容
通过 Vue 的 v-if 和 v-else 指令可以根据条件显示不同内容。定义一个布尔变量控制切换状态。
<template>
<div>
<button @click="toggleContent">切换内容</button>
<div v-if="showContent">这是第一段内容</div>
<div v-else>这是第二段内容</div>
</div>
</template>
<script>
export default {
data() {
return {
showContent: true
}
},
methods: {
toggleContent() {
this.showContent = !this.showContent
}
}
}
</script>
使用 v-show 指令切换内容
v-show 通过 CSS 的 display 属性控制元素显示隐藏,适合频繁切换的场景。

<template>
<div>
<button @click="toggleContent">切换内容</button>
<div v-show="showContent">可见内容</div>
<div v-show="!showContent">隐藏内容</div>
</div>
</template>
使用动态组件切换
通过 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>
使用 CSS 过渡效果
为内容切换添加过渡动画,提升用户体验。

<template>
<div>
<button @click="show = !show">切换</button>
<transition name="fade">
<div v-if="show">过渡效果内容</div>
</transition>
</div>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
使用计算属性切换内容
通过计算属性返回不同的内容,适合基于复杂逻辑的切换。
<template>
<div>
<button @click="toggleType">切换类型</button>
<div>{{ displayContent }}</div>
</div>
</template>
<script>
export default {
data() {
return {
contentType: 'A'
}
},
computed: {
displayContent() {
return this.contentType === 'A' ? '类型A内容' : '类型B内容'
}
},
methods: {
toggleType() {
this.contentType = this.contentType === 'A' ? 'B' : 'A'
}
}
}
</script>
结合路由切换内容
在单页应用中,可以通过 Vue Router 实现内容切换。
// router.js
const routes = [
{ path: '/content-a', component: ContentA },
{ path: '/content-b', component: ContentB }
]
<template>
<div>
<router-link to="/content-a">内容A</router-link>
<router-link to="/content-b">内容B</router-link>
<router-view></router-view>
</div>
</template>






