Uniapp页面自定义tabbar
时间: 2023-09-20 12:07:26 浏览: 99
uniapp自定义tabbar图标样式
5星 · 资源好评率100%
Uniapp提供了一种方便的方法来自定义tabbar,你可以按照以下步骤进行操作:
1. 在pages.json中设置tabBar属性为自定义tabBar的json配置文件路径:
```
{
"tabBar": {
"custom": true,
"color": "#999",
"selectedColor": "#007aff",
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "static/images/tabbar/home.png",
"selectedIconPath": "static/images/tabbar/home_selected.png"
},
{
"pagePath": "pages/mine/mine",
"text": "我的",
"iconPath": "static/images/tabbar/mine.png",
"selectedIconPath": "static/images/tabbar/mine_selected.png"
}
]
}
}
```
其中,custom属性为true表示使用自定义tabBar,list数组中包含每个tab的配置信息,包括页面路径、文字、未选中和选中状态下的图标路径等。
2. 在App.vue中添加自定义tabBar组件:
```
<template>
<div class="container">
<router-view></router-view>
<tab-bar :list="list" @tabClick="onTabClick"></tab-bar>
</div>
</template>
<script>
import TabBar from '@/components/tab-bar'
export default {
components: { TabBar },
data() {
return {
list: [
{
pagePath: '/pages/index/index',
text: '首页',
iconPath: '/static/images/tabbar/home.png',
selectedIconPath: '/static/images/tabbar/home_selected.png'
},
{
pagePath: '/pages/mine/mine',
text: '我的',
iconPath: '/static/images/tabbar/mine.png',
selectedIconPath: '/static/images/tabbar/mine_selected.png'
}
]
}
},
methods: {
onTabClick(index) {
uni.switchTab({
url: this.list[index].pagePath
})
}
}
}
</script>
```
其中,list属性为tabBar的配置信息,@tabClick为tab被点击时的回调函数,通过uni.switchTab方法切换tab对应的页面。
3. 编写自定义tabBar组件:
```
<template>
<div class="tab-bar">
<div class="tab-item" v-for="(item, index) in list" :key="index" @click="onTabClick(index)">
<img :src="currentIndex === index ? item.selectedIconPath : item.iconPath" alt="">
<span :style="{color: currentIndex === index ? selectedColor : color}">{{ item.text }}</span>
</div>
</div>
</template>
<script>
export default {
props: {
list: {
type: Array,
required: true
},
color: {
type: String,
default: '#999'
},
selectedColor: {
type: String,
default: '#007aff'
}
},
data() {
return {
currentIndex: 0
}
},
methods: {
onTabClick(index) {
if (index !== this.currentIndex) {
this.currentIndex = index
this.$emit('tabClick', index)
}
}
}
}
</script>
<style scoped>
.tab-bar {
display: flex;
justify-content: space-around;
align-items: center;
height: 50px;
box-shadow: 0 -1px 2px rgba(0, 0, 0, .1);
}
.tab-item {
display: flex;
flex-direction: column;
align-items: center;
font-size: 12px;
}
.tab-item img {
width: 24px;
height: 24px;
margin-bottom: 2px;
}
.tab-item span {
font-size: 12px;
}
</style>
```
以上就是自定义tabBar的完整代码,你可以根据自己的需求进行修改和扩展。
阅读全文