1. 程式人生 > 其它 >小程式自定義底部導航 custom-tab-bar

小程式自定義底部導航 custom-tab-bar

1. app.json  

2. 將 custom-tab-bar 放到根目錄下(pages同級)

3. custom-tab-bar  程式碼

{
  "component": true
}

Component({
  data: {
    USERTYPE:'customer',
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#3cc51f",
    listAll: [{
      type:'customer',
      pagePath: "/pages/c_home/index",
      iconPath: "/images/tabbar/home.png",
      selectedIconPath: "/images/tabbar/home-a.png",
      text: "首頁"
    }, {
      type:'customer',
      pagePath: "/pages/c_mine/index",
      iconPath: "/images/tabbar/mine.png",
      selectedIconPath: "/images/tabbar/mine-a.png",
      text: "我的"
    },
    {
      type:'business',
      pagePath: "/pages/b_home/index",
      iconPath: "/images/tabbar/b_home.png",
      selectedIconPath: "/images/tabbar/b_home-a.png",
      text: "主頁"
    }, {
      type:'business',
      pagePath: "/pages/b_mine/index",
      iconPath: "/images/tabbar/b_mine.png",
      selectedIconPath: "/images/tabbar/b_mine-a.png",
      text: "我的"
    }],
    list:[], 
  },
  observers:{
     'USERTYPE': function(newVal, oldVal){   //監聽systemId的資料變化 
      let listAll = this.data.listAll 
      let list = [] 
      if (newVal === 'business') {
        list = listAll.slice(2,4) 
      } else {
        list = listAll.slice(0,2) 
      }
      this.setData({
        list 
      })
    }
  },  
  methods: { 
    switchTab(e) { 
      const data = e.currentTarget.dataset
      const url = data.path 
      wx.switchTab({url}) 
    }
  }
})

 
<view class="tab-bar">
  <view class="tab-bar-border"></view>
  <view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab"> 
    <image src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></image>
    <view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</view>   
  </view>
</view> 

 .tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 96rpx;
  background: white;
  display: flex;
  padding-bottom: env(safe-area-inset-bottom); 
}

.tab-bar-border {
  background-color: rgba(250,250,250 0.33);
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 1px;
  transform: scaleY(0.5);
}

.tab-bar-item {
  flex: 1;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.tab-bar-item image {
  width: 27px;
  height: 27px;
}

.tab-bar-item view {
  font-size: 10px;
}

4. 登入成功本地存使用者型別

  wx.setStorageSync('USERTYPE', 'business')  or         wx.setStorageSync('USERTYPE', 'customer') 5.tabbar 頁面 onShow 
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0,
        USERTYPE:wx.getStorageSync('USERTYPE')
      })
    }

6.注意 custom-tab-bar js 程式碼 custom-tab-bar  USERTYPE 要用 

observers 否則頁面跳轉會混亂(踩過坑),之前那塊的邏輯寫到了 created 裡面