vue 实现tab
Vue 实现 Tab 切换功能
在 Vue 中实现 Tab 切换功能可以通过多种方式完成,以下是几种常见的实现方法:
使用动态组件
<template>
<div>
<button @click="currentTab = 'Tab1'">Tab 1</button>
<button @click="currentTab = 'Tab2'">Tab 2</button>
<button @click="currentTab = 'Tab3'">Tab 3</button>
<component :is="currentTab"></component>
</div>
</template>
<script>
import Tab1 from './Tab1.vue'
import Tab2 from './Tab2.vue'
import Tab3 from './Tab3.vue'
export default {
components: { Tab1, Tab2, Tab3 },
data() {
return {
currentTab: 'Tab1'
}
}
}
</script>
使用 v-show 或 v-if
<template>
<div>
<button @click="activeTab = 'tab1'">Tab 1</button>
<button @click="activeTab = 'tab2'">Tab 2</button>
<button @click="activeTab = 'tab3'">Tab 3</button>
<div v-show="activeTab === 'tab1'">Content for Tab 1</div>
<div v-show="activeTab === 'tab2'">Content for Tab 2</div>
<div v-show="activeTab === 'tab3'">Content for Tab 3</div>
</div>
</template>
<script>
export default {
data() {
return {
activeTab: 'tab1'
}
}
}
</script>
使用 Vue Router 实现路由级 Tab
// router.js
const routes = [
{ path: '/', redirect: '/tab1' },
{ path: '/tab1', component: Tab1 },
{ path: '/tab2', component: Tab2 },
{ path: '/tab3', component: Tab3 }
]
<template>
<div>
<router-link to="/tab1">Tab 1</router-link>
<router-link to="/tab2">Tab 2</router-link>
<router-link to="/tab3">Tab 3</router-link>
<router-view></router-view>
</div>
</template>
使用第三方 UI 库
许多 Vue UI 组件库如 Element UI、Vuetify 等提供了现成的 Tab 组件:
<template>
<el-tabs v-model="activeTab">
<el-tab-pane label="Tab 1" name="tab1">Content 1</el-tab-pane>
<el-tab-pane label="Tab 2" name="tab2">Content 2</el-tab-pane>
<el-tab-pane label="Tab 3" name="tab3">Content 3</el-tab-pane>
</el-tabs>
</template>
<script>
export default {
data() {
return {
activeTab: 'tab1'
}
}
}
</script>
自定义 Tab 组件
可以创建可复用的 Tab 组件:
<!-- Tabs.vue -->
<template>
<div class="tabs">
<div class="tab-headers">
<div
v-for="(tab, index) in tabs"
:key="index"
@click="selectTab(index)"
:class="{ active: currentTab === index }"
>
{{ tab.title }}
</div>
</div>
<div class="tab-content">
<slot :name="`tab-${currentTab}`"></slot>
</div>
</div>
</template>
<script>
export default {
props: {
tabs: Array,
initialTab: {
type: Number,
default: 0
}
},
data() {
return {
currentTab: this.initialTab
}
},
methods: {
selectTab(index) {
this.currentTab = index
}
}
}
</script>
<!-- 使用示例 -->
<template>
<Tabs :tabs="[
{ title: 'Tab 1' },
{ title: 'Tab 2' },
{ title: 'Tab 3' }
]">
<template #tab-0>Content 1</template>
<template #tab-1>Content 2</template>
<template #tab-2>Content 3</template>
</Tabs>
</template>
以上方法可以根据项目需求选择最适合的实现方式。简单的展示可以使用 v-show/v-if,复杂应用可以考虑动态组件或路由方案,需要快速开发可以使用第三方 UI 库。







