tabbar 实现 vue
使用 Vue Router 实现 TabBar
在 Vue 项目中,可以通过 Vue Router 和自定义组件实现 TabBar。以下是具体实现方法:
创建 TabBar 组件
<template>
<div class="tab-bar">
<router-link
v-for="(item, index) in tabList"
:key="index"
:to="item.path"
class="tab-item"
active-class="active"
>
<span class="icon">{{ item.icon }}</span>
<span class="text">{{ item.text }}</span>
</router-link>
</div>
</template>
<script>
export default {
name: 'TabBar',
data() {
return {
tabList: [
{ path: '/home', icon: '🏠', text: '首页' },
{ path: '/category', icon: '📋', text: '分类' },
{ path: '/cart', icon: '🛒', text: '购物车' },
{ path: '/profile', icon: '👤', text: '我的' }
]
}
}
}
</script>
<style scoped>
.tab-bar {
position: fixed;
left: 0;
right: 0;
bottom: 0;
display: flex;
height: 50px;
background: #f6f6f6;
box-shadow: 0 -1px 1px rgba(0, 0, 0, 0.1);
}
.tab-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #666;
text-decoration: none;
}
.tab-item.active {
color: #ff5777;
}
.icon {
margin-bottom: 2px;
font-size: 20px;
}
.text {
font-size: 12px;
}
</style>
配置 Vue Router
在 router/index.js 中配置路由:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
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 = new VueRouter({
routes
})
export default router
在主组件中使用 TabBar
在 App.vue 中引入 TabBar 组件:
<template>
<div id="app">
<router-view/>
<tab-bar/>
</div>
</template>
<script>
import TabBar from '@/components/TabBar'
export default {
name: 'App',
components: {
TabBar
}
}
</script>
<style>
#app {
padding-bottom: 50px; /* 给TabBar留出空间 */
}
</style>
使用第三方 UI 库实现
如果需要快速实现,可以使用第三方 UI 库如 Vant 的 TabBar 组件:

安装 Vant:
npm install vant
在 main.js 中引入:
import Vant from 'vant'
import 'vant/lib/index.css'
Vue.use(Vant)
使用 Vant TabBar:
<template>
<div>
<router-view/>
<van-tabbar v-model="active" route>
<van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
<van-tabbar-item icon="apps-o" to="/category">分类</van-tabbar-item>
<van-tabbar-item icon="cart-o" to="/cart">购物车</van-tabbar-item>
<van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
</van-tabbar>
</div>
</template>
<script>
export default {
data() {
return {
active: 0
}
}
}
</script>
以上方法提供了从基础实现到使用 UI 库的多种方案,可以根据项目需求选择合适的实现方式。






