vue tab实现顶部导航
vue实现顶部导航tab的方法
使用v-for动态生成tab
通过v-for指令循环生成tab项,结合v-bind动态绑定class和事件
<template>
<div class="tab-container">
<div
v-for="(tab, index) in tabs"
:key="index"
:class="['tab-item', { 'active': currentTab === index }]"
@click="switchTab(index)"
>
{{ tab.title }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 0,
tabs: [
{ title: '首页' },
{ 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: #409EFF;
border-bottom: 2px solid #409EFF;
}
</style>
使用router-link实现路由切换
当需要导航到不同路由时,可以使用router-link组件
<template>
<div class="nav-tabs">
<router-link
v-for="(item, index) in navItems"
:key="index"
:to="item.path"
active-class="active"
class="nav-item"
>
{{ item.title }}
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
navItems: [
{ title: '首页', path: '/' },
{ title: '产品', path: '/products' },
{ title: '服务', path: '/services' }
]
}
}
}
</script>
<style scoped>
.nav-tabs {
display: flex;
}
.nav-item {
padding: 12px 16px;
text-decoration: none;
color: #333;
}
.nav-item.active {
color: #409EFF;
border-bottom: 2px solid #409EFF;
}
</style>
使用第三方组件库
Element UI等UI库提供了现成的Tab组件
<template>
<el-tabs v-model="activeName" @tab-click="handleClick">
<el-tab-pane label="用户管理" name="first"></el-tab-pane>
<el-tab-pane label="配置管理" name="second"></el-tab-pane>
<el-tab-pane label="角色管理" name="third"></el-tab-pane>
</el-tabs>
</template>
<script>
export default {
data() {
return {
activeName: 'first'
}
},
methods: {
handleClick(tab) {
console.log(tab.name)
}
}
}
</script>
实现滑动指示条效果
通过动态计算和CSS过渡实现更流畅的滑动效果
<template>
<div class="sliding-tabs">
<div class="tabs-header">
<div
v-for="(tab, index) in tabs"
:key="index"
class="tab"
@click="selectTab(index)"
>
{{ tab }}
</div>
<div class="slider" :style="sliderStyle"></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: ['推荐', '热门', '最新'],
activeIndex: 0,
sliderWidth: 0
}
},
computed: {
sliderStyle() {
return {
width: `${this.sliderWidth}px`,
transform: `translateX(${this.activeIndex * 100}%)`
}
}
},
mounted() {
this.calculateSliderWidth()
},
methods: {
selectTab(index) {
this.activeIndex = index
},
calculateSliderWidth() {
const tabCount = this.tabs.length
this.sliderWidth = 100 / tabCount
}
}
}
</script>
<style scoped>
.tabs-header {
display: flex;
position: relative;
}
.tab {
flex: 1;
text-align: center;
padding: 12px 0;
cursor: pointer;
}
.slider {
position: absolute;
bottom: 0;
height: 2px;
background-color: #409EFF;
transition: transform 0.3s ease;
}
</style>






