uniapp底部导航栏点击切换图标
时间: 2023-09-12 10:07:12 浏览: 206
底部导航栏图标变换
在uni-app中,可以通过以下步骤来实现底部导航栏点击切换图标:
1. 在pages.json文件中设置底部导航栏的图标和页面路径:
```json
{
"pages": [
{
"path": "pages/home/home",
"name": "home",
"style": {
"navigationBarTitleText": "首页",
"app-plus": {
"bounce": "none"
}
}
},
{
"path": "pages/mine/mine",
"name": "mine",
"style": {
"navigationBarTitleText": "我的",
"app-plus": {
"bounce": "none"
}
}
}
],
"tabBar": {
"color": "#666",
"selectedColor": "#007aff",
"backgroundColor": "#fff",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/home/home",
"text": "首页",
"iconPath": "static/tabbar/home.png",
"selectedIconPath": "static/tabbar/home-active.png"
},
{
"pagePath": "pages/mine/mine",
"text": "我的",
"iconPath": "static/tabbar/mine.png",
"selectedIconPath": "static/tabbar/mine-active.png"
}
]
}
}
```
2. 在底部导航栏所在的页面中,监听tabBar的点击事件,并在事件处理函数中修改当前选中的图标:
```js
export default {
data() {
return {
tabBar: {},
activeIndex: 0
};
},
onShow() {
this.tabBar = this.$tabBar({
backgroundColor: "#fff",
color: "#666",
selectedColor: "#007aff",
list: [
{
text: "首页",
iconPath: "/static/tabbar/home.png",
selectedIconPath: "/static/tabbar/home-active.png",
pagePath: "/pages/home/home"
},
{
text: "我的",
iconPath: "/static/tabbar/mine.png",
selectedIconPath: "/static/tabbar/mine-active.png",
pagePath: "/pages/mine/mine"
}
]
});
this.tabBar.setActiveIndex(this.activeIndex);
},
methods: {
onTabBarItemTap(index) {
this.activeIndex = index;
this.tabBar.setActiveIndex(index);
this.tabBar.list.forEach((item, i) => {
if (i === index) {
item.iconPath = item.selectedIconPath;
} else {
item.iconPath = item.iconPath.replace("-active", "");
}
});
}
}
};
```
在模板中,可以使用onTabBarItemTap方法来监听底部导航栏的点击事件:
```html
<template>
<view class="container">
<view class="content">
<text>这是{{tabBar.list[activeIndex].text}}页面</text>
</view>
<view class="tab-bar">
<view
v-for="(item, index) in tabBar.list"
:key="index"
@tap="onTabBarItemTap(index)"
class="tab-bar-item"
:class="{ active: index === activeIndex }"
>
<image :src="index === activeIndex ? item.selectedIconPath : item.iconPath" />
<text>{{ item.text }}</text>
</view>
</view>
</view>
</template>
```
以上代码实现了底部导航栏点击切换图标的功能。
阅读全文