vue tab实现顶部导航
vue实现顶部导航tab的方法
使用v-for动态生成tab
通过v-for指令遍历数据数组动态生成tab项,结合v-bind绑定动态class控制选中状态。

<template>
<div class="tab-container">
<div
v-for="(item, index) in tabs"
:key="index"
:class="['tab-item', { 'active': currentTab === index }]"
@click="switchTab(index)"
>
{{ item.title }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 0,
tabs: [
{ title: '首页' },
{ title: '产品' },
{ title: '关于' }
]
}
},
methods: {
switchTab(index) {
this.currentTab = index
}
}
}
</script>
<style scoped>
.tab-container {
display: flex;
border-bottom: 1px solid #eee;
}
.tab-item {
padding: 12px 20px;
cursor: pointer;
}
.tab-item.active {
color: #1890ff;
border-bottom: 2px solid #1890ff;
}
</style>
使用router-link实现路由切换
当需要结合vue-router使用时,可采用router-link组件实现导航跳转。

<template>
<div class="nav-tabs">
<router-link
v-for="(item, index) in tabs"
:key="index"
:to="item.path"
active-class="active"
>
{{ item.title }}
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ title: '首页', path: '/' },
{ title: '详情', path: '/detail' }
]
}
}
}
</script>
<style scoped>
.nav-tabs {
display: flex;
}
.nav-tabs a {
padding: 10px 15px;
text-decoration: none;
}
.nav-tabs a.active {
color: red;
border-bottom: 2px solid red;
}
</style>
使用第三方组件库
Element UI等组件库提供了现成的Tab组件,可直接使用。
<template>
<el-tabs v-model="activeTab">
<el-tab-pane
v-for="item in tabs"
:key="item.name"
:label="item.label"
:name="item.name"
>
{{ item.content }}
</el-tab-pane>
</el-tabs>
</template>
<script>
export default {
data() {
return {
activeTab: 'home',
tabs: [
{ label: '首页', name: 'home', content: '首页内容' },
{ label: '用户', name: 'user', content: '用户管理' }
]
}
}
}
</script>
添加滑动动画效果
通过transition组件为tab切换添加平滑过渡效果。
<template>
<div>
<div class="tabs-header">
<!-- tab标题代码 -->
</div>
<transition name="fade">
<div class="tab-content">
{{ tabs[currentTab].content }}
</div>
</transition>
</div>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>






