tabbar 实现 vue
在 Vue 中实现 TabBar 功能可以通过多种方式完成,以下是几种常见的方法:

使用 Vue Router 结合自定义组件
创建一个自定义的 TabBar 组件,结合 Vue Router 实现路由切换。以下是一个简单的实现示例:

<template>
<div class="tab-bar">
<router-link
v-for="tab in tabs"
:key="tab.path"
:to="tab.path"
class="tab-item"
active-class="active"
>
{{ tab.name }}
</router-link>
</div>
</template>
<script>
export default {
data() {
return {
tabs: [
{ path: '/home', name: '首页' },
{ path: '/category', name: '分类' },
{ path: '/cart', name: '购物车' },
{ path: '/profile', name: '我的' },
],
};
},
};
</script>
<style>
.tab-bar {
display: flex;
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: #fff;
box-shadow: 0 -1px 1px rgba(0, 0, 0, 0.1);
}
.tab-item {
flex: 1;
text-align: center;
padding: 10px;
color: #666;
}
.tab-item.active {
color: #ff6700;
}
</style>
使用第三方 UI 库
许多 Vue UI 库提供了现成的 TabBar 组件,例如 Vant、Element UI 等。以下是使用 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>
动态切换内容
如果不需要路由跳转,可以通过动态组件或条件渲染实现内容切换:
<template>
<div>
<div class="tab-bar">
<div
v-for="(tab, index) in tabs"
:key="index"
class="tab-item"
:class="{ active: currentTab === index }"
@click="currentTab = index"
>
{{ tab.name }}
</div>
</div>
<div class="tab-content">
<component :is="tabs[currentTab].component" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 0,
tabs: [
{ name: '首页', component: 'Home' },
{ name: '分类', component: 'Category' },
{ name: '购物车', component: 'Cart' },
{ name: '我的', component: 'Profile' },
],
};
},
};
</script>
注意事项
- 如果使用路由模式,确保在
router/index.js中配置了对应的路由路径。 - 移动端开发时,通常需要固定 TabBar 在底部,并留出内容区域的空间。
- 可以通过 Vuex 或 Pinia 管理 TabBar 的状态,实现跨组件通信。






