uniapp小程序自定义tabbar
时间: 2023-06-18 21:08:20 浏览: 98
小程序自定义tabbar
UniApp小程序支持自定义TabBar,可以通过以下步骤实现:
1. 在 `manifest.json` 文件中设置 `tabBar` 字段,例如:
```
"tabBar": {
"color": "#666",
"selectedColor": "#007aff",
"backgroundColor": "#fff",
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "static/tabbar/home.png",
"selectedIconPath": "static/tabbar/home-selected.png"
},
{
"pagePath": "pages/cart/cart",
"text": "购物车",
"iconPath": "static/tabbar/cart.png",
"selectedIconPath": "static/tabbar/cart-selected.png"
},
{
"pagePath": "pages/profile/profile",
"text": "我的",
"iconPath": "static/tabbar/profile.png",
"selectedIconPath": "static/tabbar/profile-selected.png"
}
]
}
```
2. 在 `App.vue` 中添加 `tabBar` 组件,例如:
```html
<template>
<div>
<tab-bar></tab-bar>
<router-view></router-view>
</div>
</template>
<script>
import TabBar from '@/components/TabBar.vue'
export default {
components: {
TabBar
}
}
</script>
```
3. 在 `TabBar.vue` 组件中实现自定义的 TabBar 样式和交互,例如:
```html
<template>
<div class="tab-bar">
<div
v-for="(item, index) in list"
:key="index"
class="tab-bar-item"
:class="{active: index === selected}"
@click="onTabClick(index)"
>
<img :src="index === selected ? item.selectedIconPath : item.iconPath" alt="">
<span>{{ item.text }}</span>
</div>
</div>
</template>
<script>
export default {
props: {
list: {
type: Array,
required: true
},
selected: {
type: Number,
required: true
}
},
methods: {
onTabClick(index) {
if (index !== this.selected) {
uni.switchTab({
url: this.list[index].pagePath
})
}
}
}
}
</script>
<style scoped>
.tab-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: space-around;
align-items: center;
height: 50px;
background-color: #fff;
box-shadow: 0 -1px 10px rgba(0, 0, 0, .1);
}
.tab-bar-item {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 14px;
color: #666;
}
.tab-bar-item img {
width: 24px;
height: 24px;
margin-bottom: 4px;
}
.tab-bar-item.active {
color: #007aff;
}
</style>
```
这样就可以实现自定义的 TabBar 了。需要注意的是,使用自定义的 TabBar 后,原生的 TabBar 将不再显示。
阅读全文