vue实现tabbar
使用 Vue Router 实现 TabBar
安装 Vue Router 依赖
npm install vue-router
创建路由配置文件
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
创建 TabBar 组件
基础 TabBar 组件结构
<!-- components/TabBar.vue -->
<template>
<div class="tab-bar">
<router-link
v-for="tab in tabs"
:key="tab.path"
:to="tab.path"
class="tab-item"
active-class="active"
>
<span>{{ tab.title }}</span>
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ path: '/', title: '首页' },
{ path: '/about', title: '关于' }
]
}
}
}
</script>
<style>
.tab-bar {
display: flex;
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
background: #fff;
box-shadow: 0 -1px 10px rgba(0,0,0,0.1);
}
.tab-item {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
color: #666;
text-decoration: none;
}
.active {
color: #42b983;
font-weight: bold;
}
</style>
在主应用中使用 TabBar
App.vue 配置示例

<template>
<router-view />
<TabBar />
</template>
<script>
import TabBar from './components/TabBar.vue'
export default {
components: { TabBar }
}
</script>
添加图标支持
使用字体图标或 SVG
<template>
<router-link
v-for="tab in tabs"
:key="tab.path"
:to="tab.path"
class="tab-item"
active-class="active"
>
<i :class="tab.icon"></i>
<span>{{ tab.title }}</span>
</router-link>
</template>
<script>
export default {
data() {
return {
tabs: [
{ path: '/', title: '首页', icon: 'icon-home' },
{ path: '/about', title: '关于', icon: 'icon-user' }
]
}
}
}
</script>
实现动态路由匹配
动态生成 TabBar 项目

// 从路由配置自动生成 tabs
computed: {
tabs() {
return this.$router.options.routes
.filter(route => route.meta?.showInTabBar)
.map(route => ({
path: route.path,
title: route.meta?.title || route.path,
icon: route.meta?.icon
}))
}
}
路由配置添加 meta 信息
const routes = [
{
path: '/',
component: Home,
meta: {
title: '首页',
icon: 'icon-home',
showInTabBar: true
}
}
]
响应式 TabBar 设计
媒体查询适配不同屏幕
@media (min-width: 768px) {
.tab-bar {
position: static;
box-shadow: none;
border-top: 1px solid #eee;
}
}
添加过渡动画
路由视图过渡效果
<template>
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
<TabBar />
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>






