微信小程序实现自定义tabbar,并解决图标闪烁问题

微信小程序实现自定义tabbar,并解决图标闪烁问题

提示:微信小程序允许开发者根据项目UI需要自定义tabbar,实现个性化,官方文档 戳这里

demo下载地址: https://developers.weixin.qq.com/s/jiSARvmF7i55


 

使用步骤

  • 一、配置信息
  • 二、根目录创建custom-tab-bar相关文件
    • 1. custom-tab-bar/index.js
    • 2. custom-tab-bar/index.json
    • 3. custom-tab-bar/index.wxml
    • 4. custom-tab-bar/index.wxss
  • 三、tabbar页面设置 selected

 


一、配置信息

  1. 在 app.json 中的 tabBar 项指定 custom 字段,同时其余 tabBar 相关配置也补充完整;
  2. 所有 tab 页的 json 里需声明 usingComponents 项,也可以在 app.json 全局开启。
{
  "tabBar": {
    "custom": true,
    "color": "#000000",
    "selectedColor": "#000000",
    "backgroundColor": "#000000",
    "list": [
        {
          "pagePath": "page/component/index",
          "text": "组件"
        }, 
        {
          "pagePath": "page/API/index",
          "text": "接口"
        }
     ]
  },
  "usingComponents": {}
}

二、创建 tabbar 文件

1. 在代码根目录下创建 custom-tab-bar 文件!!!

custom-tab-bar/index.js
custom-tab-bar/index.json
custom-tab-bar/index.wxml
custom-tab-bar/index.wxss

2. index.js

switchTab(e) {
    const data = e.currentTarget.dataset
    const url = data.path
    wx.switchTab({url})
    this.setData({
      selected: data.index
    })
}

 

三、在 tabbar 页面

引用官网:自定义组件新增 getTabBar 接口,可获取当前页面下的自定义 tabBar 组件实例。

每个tab页内容在onShow的时候都需要通过getTabBar接口设置自定义tabbar里的selected值;

onShow() {
   if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
   }
}

注意:按理说到此,小程序自定的tabbar已经完成了,页面tabbar切换也实现了,但是在真机体验中会出现一个小的图标闪烁问题;

经过一直不妥协的查找,终于给找到了,一个小伙伴提供的在 custom-tab-bar/index.js 中将去掉一段 setdata

 

switchTab(e) {

      const dataset = e.currentTarget.dataset;

      const url = dataset.path;

      const index = dataset.index;

      wx.switchTab({ url})

      // this.setData({ selected: index })    //因为我们在tabbat页面已经通过getTabBar设置了selected, 此处就不需要再重复设置了!!!

 }

 


总结

小程序开发还在不断的更新阶段,有一些难免的小bug需要我们不断的去探索,实践,大家一起愉快的ban砖吧!!!

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值