一、需求说明
小程序 Tabbar 自定义内容样式和事件,实现个性化场景
案例如下,点击扫码图标进入扫码页面:
二、实现 Demo
1、安装 Vant Weapp
为减少重复开发,使用该组件库的 Tabbar 组件,用法见文档
2、小程序 tabBar 设置完整配置项,并开启自定义
"tabBar": {
"list": [
{
"pagePath": "pages/index/index",
"text": "首页",
"iconPath": "images/home.png",
"selectedIconPath": "images/home-active.png"
},
{
"pagePath": "pages/user/user",
"text": "个人中心",
"iconPath": "images/user.png",
"selectedIconPath": "images/user-active.png"
}
],
"custom": true
},
3、编写自定义 tabBar 文件,可参考官方教程
index.json
{
"component": true
}
index.js
// custom-tab-bar/index.js
const imgUrlPrefix = 'http://xtc-zht.oss-cn-shenzhen.aliyuncs.com/static/retail-app/tabbar'
Component({
data: {
imgUrlPrefix,
active: 0,
list: [
{
pagePath: "/pages/index/index",
text: "首页",
iconPath: "/home.png",
selectedIconPath: "/home-active.png"
},
{
pagePath: "/pages/user/user",
text: "个人中心",
iconPath: "/user.png",
selectedIconPath: "/user-active.png"
},
]
},
methods: {
onChange(event) {
this.setData({ active: event.detail });
wx.switchTab({
url: this.data.list[event.detail].pagePath,
});
},
init() {
const page = getCurrentPages().pop();
this.setData({
active: this.data.list.findIndex(item => item.pagePath === `/${page.route}`)
});
},
handleScan() {
wx.showToast({ title: '扫一扫', icon: 'none' })
}
}
})
index.wxml
<!-- custom-tab-bar/index.wxml -->
<van-tabbar
active="{{ active }}"
inactive-color="#191919"
active-color="#FF7A03"
bind:change="onChange"
>
<block wx:for="{{ list }}" wx:for-item="tab" wx:key="index">
<van-icon
wx:if="{{ index === 1 }}"
name="{{ imgUrlPrefix + '/scan.png' }}"
size="132rpx"
custom-class="scan-custom-class"
bind:click="handleScan"
/>
<van-tabbar-item wx:key="index" data-path="{{ tab.pagePath }}">
{{ tab.text }}
<van-icon slot="icon" name="{{ imgUrlPrefix + tab.iconPath }}" />
<van-icon slot="icon-active" name="{{ imgUrlPrefix + tab.selectedIconPath }}" />
</van-tabbar-item>
</block>
</van-tabbar>
index.less
// custom-tab-bar/index.wxss
.scan-custom-class {
position: relative;
z-index: 10;
margin-top: -40rpx;
}
4、在 tab 页面 onShow 钩子调用 init 方法,维护路由栈正确性
index 页面
user 页面