vue底部tabbar实现
实现底部 TabBar 的基本方法
在 Vue 中实现底部 TabBar 可以通过多种方式完成,常见的有使用第三方 UI 库或自定义组件。以下是两种主流实现方式:
使用第三方 UI 库(如 Vant)
安装 Vant 库后,直接使用 van-tabbar 组件即可快速实现底部导航。示例代码如下:
<template>
<van-tabbar v-model="active">
<van-tabbar-item icon="home-o">首页</van-tabbar-item>
<van-tabbar-item icon="search">搜索</van-tabbar-item>
<van-tabbar-item icon="friends-o">好友</van-tabbar-item>
<van-tabbar-item icon="setting-o">设置</van-tabbar-item>
</van-tabbar>
</template>
<script>
export default {
data() {
return {
active: 0
}
}
}
</script>
自定义 TabBar 组件
创建一个自定义组件 TabBar.vue,通过路由切换实现导航功能:
<template>
<div class="tab-bar">
<div
v-for="(item, index) in tabs"
:key="index"
class="tab-item"
:class="{ active: currentIndex === index }"
@click="switchTab(index, item.path)"
>
<span>{{ item.title }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
tabs: [
{ title: '首页', path: '/home' },
{ title: '分类', path: '/category' },
{ title: '购物车', path: '/cart' },
{ title: '我的', path: '/mine' }
]
}
},
methods: {
switchTab(index, path) {
this.currentIndex = index
this.$router.push(path)
}
}
}
</script>
<style scoped>
.tab-bar {
position: fixed;
bottom: 0;
width: 100%;
display: flex;
background: #fff;
}
.tab-item {
flex: 1;
text-align: center;
}
.active {
color: red;
}
</style>
结合 Vue Router 的实现
确保在路由配置中为每个 Tab 页面设置对应路由:
const routes = [
{ path: '/home', component: Home },
{ path: '/category', component: Category },
{ path: '/cart', component: Cart },
{ path: '/mine', component: Mine }
]
在 App.vue 中引入 TabBar 组件时,注意为路由视图留出空间:
<template>
<div id="app">
<router-view/>
<TabBar/>
</div>
</template>
动态高亮当前 Tab
通过监听路由变化自动更新高亮状态:
watch: {
'$route.path': {
handler(newVal) {
const index = this.tabs.findIndex(item => item.path === newVal)
if (index !== -1) {
this.currentIndex = index
}
},
immediate: true
}
}
添加过渡动画
为 Tab 切换添加过渡效果可提升用户体验:
<router-view v-slot="{ Component }">
<transition name="fade">
<component :is="Component" />
</transition>
</router-view>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>
移动端适配注意事项
针对移动端需要额外处理:

- 设置 viewport meta 标签
- 添加 iOS 底部安全区域适配
- 防止点击高亮效果
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<style>
.tab-bar {
padding-bottom: env(safe-area-inset-bottom);
}
.tab-item {
-webkit-tap-highlight-color: transparent;
}
</style>






