vue实现tab表切换
Vue 实现 Tab 标签页切换
方法一:使用 v-if 和 v-show 控制显示
通过 v-if 或 v-show 动态切换不同标签页内容,结合 v-for 渲染标签按钮。
<template>
<div>
<div class="tabs">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = index"
:class="{ active: currentTab === index }"
>
{{ tab.name }}
</button>
</div>
<div class="content">
<div v-if="currentTab === 0">内容1</div>
<div v-if="currentTab === 1">内容2</div>
<div v-if="currentTab === 2">内容3</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 0,
tabs: [
{ name: '标签1' },
{ name: '标签2' },
{ name: '标签3' }
]
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
方法二:动态组件 <component :is>
通过动态组件切换不同子组件,适合复杂标签页内容。
<template>
<div>
<div class="tabs">
<button
v-for="(tab, index) in tabs"
:key="index"
@click="currentTab = tab.component"
:class="{ active: currentTab === tab.component }"
>
{{ tab.name }}
</button>
</div>
<component :is="currentTab" />
</div>
</template>
<script>
import Tab1 from './Tab1.vue'
import Tab2 from './Tab2.vue'
export default {
components: { Tab1, Tab2 },
data() {
return {
currentTab: 'Tab1',
tabs: [
{ name: '标签1', component: 'Tab1' },
{ name: '标签2', component: 'Tab2' }
]
}
}
}
</script>
方法三:使用 Vue Router 实现路由标签页
通过路由切换实现标签页,适合多页面应用。
<template>
<div>
<router-link
v-for="(tab, index) in tabs"
:key="index"
:to="tab.path"
active-class="active"
>
{{ tab.name }}
</router-link>
<router-view />
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ name: '首页', path: '/' },
{ name: '关于', path: '/about' }
]
}
}
}
</script>
优化技巧
-
过渡动画:为标签页切换添加
<transition>效果。<transition name="fade" mode="out-in"> <component :is="currentTab" /> </transition> -
状态保持:使用
<keep-alive>缓存标签页状态。<keep-alive> <component :is="currentTab" /> </keep-alive> -
响应式设计:通过 CSS Flex 或 Grid 布局适配移动端。
注意事项
- 如果标签页内容较多,优先使用
v-show避免频繁 DOM 操作。 - 动态组件需提前注册或在
components中引入。 - 路由模式需配置
vue-router并定义对应路径的组件。







