uniapp实现tabBar
时间: 2025-07-04 11:09:52 浏览: 13
在 UniApp 中实现底部导航栏(tabBar)可以通过两种方式完成:一种是使用原生的 `pages.json` 配置文件设置标准的 tabBar,另一种是通过自定义组件来实现更复杂的样式和功能。以下将分别介绍这两种方法。
### 方法一:使用 pages.json 实现原生 tabbar
在 `pages.json` 文件中配置 `tabBar` 属性即可快速创建底部导航栏。每个 tab 项可以指定页面路径、图标路径、选中图标路径以及文字描述。这种方式适用于简单的 tab 样式需求,且不支持中间按钮凸起等高级样式。
```json
{
"tabBar": {
"color": "#BBBAC7",
"selectedColor": "#2c2c2c",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/tabbar/index/index",
"iconPath": "/static/tabbar/index1.png",
"selectedIconPath": "/static/tabbar/index1_selected.png",
"text": "首页"
},
{
"pagePath": "pages/tabbar/learn/learn",
"iconPath": "/static/tabbar/learn.png",
"selectedIconPath": "/static/tabbar/learn_selected.png",
"text": "学习"
},
{
"pagePath": "pages/tabbar/home/home",
"iconPath": "/static/tabbar/home.png",
"selectedIconPath": "/static/tabbar/home_selected.png",
"text": "我的"
}
]
}
}
```
该配置会生成一个包含三个 tab 的底部导航栏,分别对应“首页”、“学习”和“我的”页面[^2]。
### 方法二:自定义 tabbar 组件(支持复杂样式)
如果需要实现更复杂的样式,比如中间按钮凸起、自定义颜色或动画效果,则需使用自定义组件的方式。首先创建一个 `TabBar.vue` 组件,并在目标页面中引入并注册该组件。
#### TabBar.vue 示例代码:
```vue
<template>
<view class="custom-tabbar">
<view
v-for="(item, index) in tabBarList"
:key="index"
@click="switchTab(item.pagePath)"
:class="['tab-item', { active: item.isActive }]"
>
<image :src="item.isActive ? item.selectedIconPath : item.iconPath" mode="aspectFit"></image>
<text>{{ item.text }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
tabBarList: [
{
pagePath: 'pages/tabbar/index/index',
iconPath: '/static/tabbar/index1.png',
selectedIconPath: '/static/tabbar/index1_selected.png',
text: '首页',
isActive: true
},
{
pagePath: 'pages/tabbar/learn/learn',
iconPath: '/static/tabbar/learn.png',
selectedIconPath: '/static/tabbar/learn_selected.png',
text: '学习',
isActive: false
},
{
pagePath: 'pages/tabbar/home/home',
iconPath: '/static/tabbar/home.png',
selectedIconPath: '/static/tabbar/home_selected.png',
text: '我的',
isActive: false
}
]
};
},
methods: {
switchTab(pagePath) {
uni.switchTab({
url: `/${pagePath}`
});
this.tabBarList.forEach(item => {
item.isActive = (item.pagePath === pagePath);
});
}
}
};
</script>
<style scoped>
.custom-tabbar {
display: flex;
justify-content: space-around;
align-items: center;
height: 60px;
background-color: #fff;
border-top: 1px solid #eee;
}
.tab-item {
text-align: center;
color: #bbbac7;
}
.tab-item.active {
color: #2c2c2c;
}
.tab-item image {
width: 30px;
height: 30px;
}
</style>
```
#### 页面中使用自定义 tabbar:
```vue
<template>
<view>
<!-- 页面主体内容 -->
<TabBar />
</view>
</template>
<script>
import TabBar from '@/components/Tabbar/Tabbar.vue';
export default {
components: {
TabBar
}
};
</script>
```
通过自定义组件方式可以灵活控制 tabbar 的外观与行为,例如添加中间凸起按钮、动态切换状态、响应点击事件等[^1]。
---
阅读全文
相关推荐


















