当前位置: 首页 > Web前端 > CSS

如何在小程序中实现自定义tabBar

时间:2023-03-30 23:34:00 CSS

背景由于微信默认的tabbar是官方组件,优先级最高,我们自己的组件的遮罩层无法覆盖。为了解决这个问题,我们可以使用微信提供的自定义tabBar功能。官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.html实现效果:实现方法在根目录下创建一个custom-tab-bar组件project,file名称为index,如图在app.json中设置tabBar为custom,这里的list必须定义,否则会报错编写tabbar代码wxml{{item.text}}jsComponent({data:{selected:0,list:[{"iconPath":"/static/tabbar/index.png","selectedIconPath":"/static/tabbar/index2.png","pagePath":"/pages/index/index","text":"Home"},{"iconPath":"/static/tabbar/activity.png","selectedIconPath":"/static/tabbar/activityity2.png","pagePath":"/pages/find/find","text":"Activity"},{"iconPath":"/static/tabbar/mall.png","selectedIconPath":"/static/tabbar/mall2.png","pagePath":"/pages/pageConfig/configIndex","text":"商城"},{"iconPath":"/static/tabbar/my.png","selectedIconPath":"/static/tabbar/my2.png","pagePath":"/pages/my/my","text":"My"}]},方法:{handleClick(e){letpath=e.currentTarget.dataset.path;letindex=e.currentTarget.dataset.index;wx.switchTab({url:path})this.setData({selected:index})}}});wxss特殊说明:自定义tabbarlevel默认为9999(非官方描述,自己测的结果),我这里用的less会编译成wxss.bar{位置:绝对;底部:0;左:0;右:0;高度:50px;显示:弹性;证明内容:空间周围;背景色:#fff;padding-bottom:env(safe-area-inset-bottom);&__item{显示:flex;弹性方向:列;对齐项目:居中;证明内容:居中;}&__img{宽度:24px;高度:24px;底部边距:2px;}&__text{字体大小:10px;}&__active{.bar__text{颜色:#487271;}}}json{"component":true,"usingComponents":{}}完成以上步骤后,t??arbar组件就写好了,接下来就是使用自定义的tabBar组件,不需要手动注册,页面定义在列表中将自动加载此组件。但需要通过以下方法手动指定高亮选项://建议在onShow方法中调用,选中值为索引值onShow(){this.getTabBar().setData({selected:0})}处理padding值由于使用了自定义的tabbar,需要在页面上使用tababr设置底部padding,防止内容被覆盖。你可以在app.wxss中定义一个全局样式,然后在相应的页面上加上这个类名。.global__fix_tabbar{padding-bottom:calc(100rpx+env(safe-area-inset-bottom));}最终效果我们的小程序使用了vant-weapp组件库。对于popup组件,设置高一点,就可以覆盖tabbar效果如下: