小程序如何自定义tabbar
发布于 2 年前 作者 ushi 1201 次浏览 来自 分享

如何自定义底部tabbar 组件呢?

index.js 的内容:

Component({
  data: {
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#3cc51f",
    list: [{
      pagePath: "/index/index",
      iconPath: "/image/icon_component.png",
      selectedIconPath: "/image/icon_component_HL.png",
      text: "组件"
    }, {
      pagePath: "/index/index2",
      iconPath: "/image/icon_API.png",
      selectedIconPath: "/image/icon_API_HL.png",
      text: "接口"
    }]
  },
  attached() {
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({url})
      this.setData({
        selected: data.index
      })
    }
  }
})

index.json的内容:

{
  "component"true
}

index.wxml的内容:

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

index.wxss的内容

.tab-bar {
  position: fixed;
  bottom0;
  left0;
  right0;
  height48px;
  background: white;
  display: flex;
  padding-bottomenv(safe-area-inset-bottom);
}

.tab-bar-border {
  background-colorrgba(0000.33);
  position: absolute;
  left0;
  top0;
  width100%;
  height1px;
  transformscaleY(0.5);
}

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

.tab-bar-item cover-image {
  width27px;
  height27px;
}

.tab-bar-item cover-view {
  font-size10px;
}

效果:

回到顶部