微信小程序-自定义底部导航

2021-10-27  本文已影响0人  懿小诺

1.将下面文件放到custom-tab-bar文件夹下

<cover-view class="tab-bar" style='height:{{isIphoneX?166:120}}rpx;'>
  <cover-view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
   
    <cover-image class='cover-image' src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></cover-image>
    <cover-view class="cover-view" style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</cover-view>
  </cover-view>
</cover-view>
const app = getApp();
Component({
  data: {
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#E4322E",
    list: [{
      pagePath: "/pages/home/home",
      iconPath: "/assets/imgs/yundan_icon@2x.png",
      selectedIconPath: "/assets/imgs/yundandianji_icon@2x.png",
      text: "我的运单",
      isSpecial: false
    },
    {
      pagePath: "/pages/goods/goods",
      iconPath: "/assets/imgs/huoyuan_icon@2x.png",
      selectedIconPath: "/assets/imgs/huoyuandianji_icon@2x.png",
      text: "专属货源",
      isSpecial: false
    },
   ],
    //适配IphoneX的屏幕底部横线
    isIphoneX: app.globalData.isIphoneX
  },
  attached() {},
  methods: {
    switchTab(e) {
      const dataset = e.currentTarget.dataset
      const path = dataset.path
      const index = dataset.index
      // //正常的tabbar切换界面
      if (path == "/pages/home/home" || path == "/pages/mine/mine") {
        app.globalData.fromType = 'tab1'
      }
      console.log('path',path);
      wx.switchTab({
        url: path
      })
      this.setData({
        selected: index,
      })
    }
  }
})

{
  "component": true
}
.tab-bar {
  position: fixed;
  bottom: 0px;
  left: 0px;
  right: 0px;
  width: 100%;
  /* height: 80rpx; */
  background: white;
  display: flex;
  flex-direction: row;
  font-size: 30rpx;
  /* padding-top: 10rpx; */
  align-items: center;
  border-top: 2rpx solid #e4e4e4;
}

.tab-bar-item {
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  flex-direction: column;
  /* padding-top: 26rpx; */
}

.cover-image {
  width: 48rpx !important;
  height: 48rpx !important;
}
.tab-bar-item .cover-view {
  font-size: 30rpx;
  margin-top: 4rpx;
}

2.在app.json中将导航配置参数custom改为true

3.在对应的页面中onshow方法里写 如下代码

对应的是底部导航选中效果selected对应的值是底部导航的数组下标

if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 0
            })
        }
上一篇 下一篇

猜你喜欢

热点阅读