vue底部tabbar实现
Vue 底部 TabBar 实现方法
使用 Vue Router 结合自定义组件
在 Vue 项目中创建一个自定义的 TabBar 组件,结合 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)"
>
<span class="icon">{{ item.icon }}</span>
<span class="text">{{ item.text }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ path: '/home', text: '首页', icon: 'H' },
{ path: '/category', text: '分类', icon: 'C' },
{ path: '/cart', text: '购物车', icon: 'S' },
{ path: '/profile', text: '我的', icon: 'P' }
]
}
},
computed: {
currentRoute() {
return this.$route.path
}
},
methods: {
switchTab(path) {
this.$router.push(path)
}
}
}
</script>
<style scoped>
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
display: flex;
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;
}
.active {
color: #42b983;
}
</style>
使用第三方 UI 库
Vant、Element UI 等流行 UI 框架提供了现成的 TabBar 组件。
以 Vant 为例:
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>
移动端适配技巧
添加 viewport meta 标签确保在移动设备上正常显示:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
使用 rem 或 vw 单位实现响应式布局:
.tab-bar {
height: 3.125rem; /* 50px / 16px = 3.125rem */
}
路由配置示例
确保 Vue Router 配置了对应的路由:
const routes = [
{ path: '/home', component: Home },
{ path: '/category', component: Category },
{ path: '/cart', component: Cart },
{ path: '/profile', component: Profile }
]
状态保持方案
使用 keep-alive 缓存页面状态:
<keep-alive>
<router-view></router-view>
</keep-alive>






