vue 实现点击tab切换
Vue 实现 Tab 切换功能
基础实现(v-show/v-if + 事件)
通过 v-show 或 v-if 控制内容显示,配合点击事件切换状态:
<template>
<div>
<div class="tabs">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = index"
:class="{ active: currentTab === index }"
>
{{ tab.title }}
</button>
</div>
<div class="content">
<div v-show="currentTab === 0">内容1</div>
<div v-show="currentTab === 1">内容2</div>
<!-- 或使用动态渲染 -->
<div>{{ tabs[currentTab].content }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 0,
tabs: [
{ title: 'Tab1', content: '内容1' },
{ title: 'Tab2', content: '内容2' }
]
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
动态组件实现(component + is)
通过动态组件实现更灵活的切换:
<template>
<div>
<button
v-for="(tab, name) in tabs"
:key="name"
@click="currentTab = name"
>
{{ tab.title }}
</button>
<component :is="currentTabComponent"></component>
</div>
</template>
<script>
import Tab1 from './Tab1.vue'
import Tab2 from './Tab2.vue'
export default {
components: { Tab1, Tab2 },
data() {
return {
currentTab: 'Tab1',
tabs: {
Tab1: { title: '标签1' },
Tab2: { title: '标签2' }
}
}
},
computed: {
currentTabComponent() {
return this.currentTab
}
}
}
</script>
路由集成方案
结合 vue-router 实现带 URL 状态的 Tab:
// router.js
const routes = [
{ path: '/tab1', component: Tab1 },
{ path: '/tab2', component: Tab2 }
]
<template>
<router-link
v-for="tab in tabs"
:key="tab.path"
:to="tab.path"
active-class="active"
>
{{ tab.title }}
</router-link>
<router-view></router-view>
</template>
动画过渡效果
为切换添加过渡动画:
<transition name="fade" mode="out-in">
<component :is="currentTabComponent"></component>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
注意事项
- 频繁切换建议使用
v-show避免组件重渲染 - 需要保持状态时使用
keep-alive包裹动态组件 - 移动端可结合手势库实现滑动切换
- 复杂场景可使用专门的状态管理(如 Pinia)维护 Tab 状态
以上方案可根据实际需求组合使用,基础项目通常采用第一种方案即可满足需求,大型应用建议采用路由集成方案。







