1. 程式人生 > >微信小程式開發---自定義tabBar

微信小程式開發---自定義tabBar

最近開發微信小程式,公司要求做一個類似閒魚的tabbar,但是網上大多資料的tabbar都會在頁面切換的時候重新渲染,所以我寫了一個不會重新渲染的tabbar,有需要的直接拿走不謝。https://github.com/SuRuiGit/wxapp-customTabbar

使用步驟如下:

第一步:找到專案中的tabbarComponent目錄,拷貝到你的工程中,然後將tabbarComponent->icon圖示替換成你自己的tabbar圖片

第二步:到app.json中配置tabBar,這裡我就不細說了,只強調閒魚的tabbar中間的按鈕是跳到二級頁面,所以不配置在tabBar的list中

第三步:在app.js的onLaunch方法中呼叫wx.hideTabBar();隱藏系統自帶的tabBar

第四步:在app.js中的globalData中加入自定義tabbar的引數,再加入一個方法給tabBar.list配置中的頁面使用,程式碼如下

globalData: {
    userInfo: null,
    tabBar: {
      "backgroundColor": "#ffffff",
      "color": "#979795",
      "selectedColor": "#1c1c1b",
      "list": [
        {
          "pagePath": "/page/index/index",
          "iconPath": "icon/icon_home.png",
          "selectedIconPath": "icon/icon_home_HL.png",
          "text": "首頁"
        },
        {
          "pagePath": "/page/myRelease/index",
          "iconPath": "icon/icon_release.png",
          "isSpecial": true,
          "text": "釋出"
        },
        {
          "pagePath": "/page/mine/index",
          "iconPath": "icon/icon_mine.png",
          "selectedIconPath": "icon/icon_mine_HL.png",
          "text": "我的"
        }
      ]
    }
  }
editTabbar: function() {
    let tabbar = this.globalData.tabBar;
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    _this.setData({
      tabbar: tabbar
    });
  },

第五步:在tabBar的list中配置的頁面的.js檔案的data中加入tabbar:{},並在onload方法中呼叫app.editTabbar();

第六步:在tabBar的list中配置的頁面的.json檔案中加入

"usingComponents": {

"tabbar": "../../tabbarComponent/tabbar"

}

在.wxml檔案中加入<tabbar tabbar="{{tabbar}}"></tabbar>

到目前為止,自定義tabbar就完成啦,撒花!!!!!