vue实现移动端tabbar
实现移动端 TabBar 的方法
使用 Vue Router 结合自定义组件
创建一个 TabBar.vue 组件,包含底部导航栏的布局和逻辑。通过 v-for 渲染导航项,结合 vue-router 实现路由切换。
<template>
<div class="tab-bar">
<div
v-for="(item, index) in tabs"
:key="index"
class="tab-item"
:class="{ active: currentRoute === item.path }"
@click="switchTab(item.path)"
>
<i :class="item.icon"></i>
<span>{{ item.title }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ title: '首页', path: '/home', icon: 'icon-home' },
{ title: '分类', path: '/category', icon: 'icon-category' },
{ title: '购物车', path: '/cart', icon: 'icon-cart' },
{ title: '我的', path: '/profile', icon: 'icon-profile' }
],
currentRoute: '/home'
}
},
methods: {
switchTab(path) {
this.currentRoute = path
this.$router.push(path)
}
}
}
</script>
<style scoped>
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
height: 50px;
background: #fff;
box-shadow: 0 -1px 10px rgba(0,0,0,0.1);
}
.tab-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: 12px;
}
.tab-item.active {
color: #ff6700;
}
</style>
在 App.vue 中引入 TabBar
确保 TabBar 固定在页面底部,并为主内容区域设置底部内边距。

<template>
<div id="app">
<router-view/>
<TabBar/>
</div>
</template>
<script>
import TabBar from './components/TabBar.vue'
export default {
components: {
TabBar
}
}
</script>
<style>
#app {
padding-bottom: 50px; /* 与 TabBar 高度一致 */
}
</style>
配置 Vue Router
在路由配置中为每个 Tab 项设置对应的路由组件。
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Category from './views/Category.vue'
import Cart from './views/Cart.vue'
import Profile from './views/Profile.vue'
Vue.use(Router)
export default new Router({
routes: [
{ path: '/', redirect: '/home' },
{ path: '/home', component: Home },
{ path: '/category', component: Category },
{ path: '/cart', component: Cart },
{ path: '/profile', component: Profile }
]
})
添加过渡效果
为路由切换添加平滑的过渡动画,提升用户体验。

<template>
<div id="app">
<transition name="fade">
<router-view/>
</transition>
<TabBar/>
</div>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
响应式设计
通过媒体查询确保 TabBar 在不同设备上显示正常。
@media (max-width: 768px) {
.tab-bar {
height: 60px;
}
#app {
padding-bottom: 60px;
}
}
使用第三方 UI 库
如果需要快速实现,可以使用 Vant 等移动端 UI 库的 TabBar 组件。
npm install vant
<template>
<van-tabbar v-model="active" fixed>
<van-tabbar-item icon="home-o">首页</van-tabbar-item>
<van-tabbar-item icon="search">分类</van-tabbar-item>
<van-tabbar-item icon="cart-o">购物车</van-tabbar-item>
<van-tabbar-item icon="user-o">我的</van-tabbar-item>
</van-tabbar>
</template>
<script>
import { Tabbar, TabbarItem } from 'vant'
export default {
components: {
[Tabbar.name]: Tabbar,
[TabbarItem.name]: TabbarItem
},
data() {
return {
active: 0
}
}
}
</script>






