uniapp如何自定义tabBar
时间: 2024-03-07 17:44:44 浏览: 110
在UniApp中,可以通过自定义tabBar来实现个性化的底部导航栏。以下是一种常见的实现方式:
1. 在`pages.json`文件中配置底部导航栏的页面路径和图标:
```json
"tabBar": {
"color": "#999999",
"selectedColor": "#007AFF",
"backgroundColor": "#ffffff",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/home/home",
"text": "首页",
"iconPath": "static/tabbar/home.png",
"selectedIconPath": "static/tabbar/home-selected.png"
},
{
"pagePath": "pages/category/category",
"text": "分类",
"iconPath": "static/tabbar/category.png",
"selectedIconPath": "static/tabbar/category-selected.png"
},
// 其他页面...
]
}
```
在上述配置中,`pagePath`表示对应的页面路径,`text`表示显示的文本,`iconPath`和`selectedIconPath`表示未选中和选中状态的图标路径。
2. 在各个页面的`<template>`中添加一个自定义的tabBar组件:
```html
<template>
<view>
<!-- 页面内容 -->
</view>
<custom-tab-bar></custom-tab-bar>
</template>
```
这里的`custom-tab-bar`是自定义的组件名称,可以根据实际情况进行修改。
3. 创建一个名为`custom-tab-bar.vue`的组件文件,并在其中编写自定义的底部导航栏布局和逻辑:
```html
<template>
<view class="tab-bar">
<view v-for="(item, index) in tabBarList" :key="index" @click="switchTab(index)">
<image :src="item.selected ? item.selectedIconPath : item.iconPath"></image>
<text :class="item.selected ? 'active' : ''">{{ item.text }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
tabBarList: [
{
pagePath: "pages/home/home",
text: "首页",
iconPath: "static/tabbar/home.png",
selectedIconPath: "static/tabbar/home-selected.png",
selected: true
},
{
pagePath: "pages/category/category",
text: "分类",
iconPath: "static/tabbar/category.png",
selectedIconPath: "static/tabbar/category-selected.png",
selected: false
},
// 其他页面...
]
};
},
methods: {
switchTab(index) {
const url = "/" + this.tabBarList[index].pagePath;
uni.switchTab({ url });
}
}
};
</script>
<style>
.tab-bar {
display: flex;
justify-content: space-around;
align-items: center;
height: 50px;
background-color: #ffffff;
border-top: 1px solid #dddddd;
}
.tab-bar view {
display: flex;
flex-direction: column;
align-items: center;
}
.tab-bar image {
width: 24px;
height: 24px;
}
.tab-bar text {
font-size: 12px;
margin-top: 4px;
}
.tab-bar .active {
color: #007aff;
}
</style>
```
在上述代码中,`tabBarList`数组存储了底部导航栏的配置信息,`switchTab`方法用于切换页面。
通过以上步骤,就可以实现自定义的底部导航栏了。
阅读全文
相关推荐















