实现uniapp小程序自定义tabbar的代码
时间: 2023-10-14 13:09:58 浏览: 167
1. 在uniapp项目的pages文件夹下创建一个tabbar文件夹,里面放置每个tab对应的页面。
2. 在App.vue中添加自定义tabbar,代码如下:
```vue
<template>
<div class="app">
<tabbar :list="tabbarList" :active="active" @change="tabbarChange"></tabbar>
<router-view></router-view>
</div>
</template>
<script>
import tabbar from "@/components/tabbar.vue";
export default {
components: {
tabbar,
},
data() {
return {
active: 0,
tabbarList: [
{
icon: "home",
text: "首页",
path: "/pages/tabbar/home/home",
},
{
icon: "cart",
text: "购物车",
path: "/pages/tabbar/cart/cart",
},
{
icon: "user",
text: "我的",
path: "/pages/tabbar/user/user",
},
],
};
},
methods: {
tabbarChange(index) {
this.active = index;
uni.switchTab({
url: this.tabbarList[index].path,
});
},
},
};
</script>
```
3. 在components文件夹下创建tabbar.vue组件,代码如下:
```vue
<template>
<div class="tabbar">
<div class="tabbar-item" v-for="(item, index) in list" :key="index" @click="change(index)">
<i :class="'iconfont icon-' + item.icon" :style="{color: index === active ? activeColor : inactiveColor}"></i>
<span :style="{color: index === active ? activeColor : inactiveColor}">{{item.text}}</span>
</div>
</div>
</template>
<script>
export default {
props: {
list: {
type: Array,
default: () => [],
},
active: {
type: Number,
default: 0,
},
activeColor: {
type: String,
default: "#007AFF",
},
inactiveColor: {
type: String,
default: "#8E8E93",
},
},
methods: {
change(index) {
if (index !== this.active) {
this.$emit("change", index);
}
},
},
};
</script>
<style>
.tabbar {
display: flex;
justify-content: space-between;
align-items: center;
height: 50px;
background-color: #fff;
border-top: 1px solid #e5e5e5;
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 999;
}
.tabbar-item {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
flex: 1;
font-size: 12px;
cursor: pointer;
}
.tabbar-item i {
font-size: 22px;
margin-bottom: 2px;
}
</style>
```
4. 在manifest.json中配置tabBar,代码如下:
```json
{
"tabBar": {
"color": "#8E8E93",
"selectedColor": "#007AFF",
"backgroundColor": "#ffffff",
"list": [
{
"pagePath": "pages/tabbar/home/home",
"text": "首页",
"iconPath": "static/tabbar/home.png",
"selectedIconPath": "static/tabbar/home-active.png"
},
{
"pagePath": "pages/tabbar/cart/cart",
"text": "购物车",
"iconPath": "static/tabbar/cart.png",
"selectedIconPath": "static/tabbar/cart-active.png"
},
{
"pagePath": "pages/tabbar/user/user",
"text": "我的",
"iconPath": "static/tabbar/user.png",
"selectedIconPath": "static/tabbar/user-active.png"
}
]
}
}
```
注意:manifest.json中的tabBar配置只是为了在微信小程序中显示原生tabbar,不会影响自定义tabbar的显示。而App.vue中的tabbar组件才是自定义tabbar的实现。
阅读全文