tabbar 实现 vue
使用 Vue Router 实现 TabBar
在 Vue 项目中,可以通过 Vue Router 结合自定义组件实现 TabBar。创建一个 TabBar.vue 组件,定义导航项并与路由关联。
<template>
<div class="tab-bar">
<router-link
v-for="(item, index) in tabItems"
:key="index"
:to="item.path"
class="tab-item"
active-class="active">
{{ item.title }}
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
tabItems: [
{ title: '首页', path: '/home' },
{ title: '分类', path: '/category' },
{ title: '购物车', path: '/cart' },
{ title: '我的', path: '/profile' }
]
}
}
}
</script>
<style scoped>
.tab-bar {
display: flex;
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: #fff;
box-shadow: 0 -1px 1px rgba(0,0,0,0.1);
}
.tab-item {
flex: 1;
text-align: center;
padding: 8px 0;
}
.active {
color: #ff6700;
}
</style>
配置 Vue Router 路由
在 router/index.js 中配置与 TabBar 关联的路由,确保路径匹配。

import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{ path: '/home', component: () => import('@/views/Home.vue') },
{ path: '/category', component: () => import('@/views/Category.vue') },
{ path: '/cart', component: () => import('@/views/Cart.vue') },
{ path: '/profile', component: () => import('@/views/Profile.vue') },
{ path: '/', redirect: '/home' }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
动态高亮当前 Tab
通过 Vue Router 的 route 对象动态判断当前路由,添加高亮样式。修改 TabBar.vue 的模板部分:

<template>
<div class="tab-bar">
<div
v-for="(item, index) in tabItems"
:key="index"
class="tab-item"
:class="{ active: $route.path === item.path }"
@click="navigateTo(item.path)">
{{ item.title }}
</div>
</div>
</template>
<script>
export default {
methods: {
navigateTo(path) {
this.$router.push(path)
}
}
}
</script>
添加图标支持
结合第三方图标库(如 Font Awesome 或 Ionicons)增强 TabBar 的视觉效果。
<template>
<div class="tab-bar">
<div
v-for="(item, index) in tabItems"
:key="index"
class="tab-item"
:class="{ active: $route.path === item.path }"
@click="navigateTo(item.path)">
<i :class="item.icon"></i>
<span>{{ item.title }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabItems: [
{ title: '首页', path: '/home', icon: 'fas fa-home' },
{ title: '分类', path: '/category', icon: 'fas fa-list' },
{ title: '购物车', path: '/cart', icon: 'fas fa-shopping-cart' },
{ title: '我的', path: '/profile', icon: 'fas fa-user' }
]
}
}
}
</script>
响应式设计优化
通过媒体查询调整 TabBar 在不同屏幕尺寸下的表现。
@media (max-width: 480px) {
.tab-bar {
height: 50px;
}
.tab-item {
font-size: 12px;
}
}






