微信小程序自定义一个简单的tab-bar

784 阅读2分钟

由于微信小程序默认的 tabBar 不美观,所以自定义了一个自己封装的tabbar。查了一下文档 自定义 tabBar 发现有这个方法,有思路了就赶紧搞起来,自己封装的tabbar所以很好去控制需要展示的样式,以下是我的开发经验分享,tabbar的图片也是网上找的。

效果展示:

WechatIMG231.jpg

一、自定义tabbar栏配置

  • app.json中添加tabBar信息,custom设为true
  • WechatIMG227.jpg
  • 虽然是自己定义的tabbar 但是 tabbar里面的 list 也要把底部的tabbar的配置加上去, 不然在点击的时候不会生效的, (本来以为不用定义,结果不行),
  • WechatIMG228.jpg

2.更改tabBar

  • 在根目录下创建 custom-tab-bar 文件夹,并在该文件夹下新建 Component,或者新建 Page,但是这种创建方式需要自己改动一些代码,在这里我们选用新建 Component 的方式,不需要自己去引入, 小程序会自动去引用的
  • WechatIMG229.jpg
index.wxml的代码:
  • WechatIMG230.jpg
index.js的代码:
Component({
  data: {
    active: 0,
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#333",
    list: [
      {
      pagePath: "/pages/index/index",
      iconPath: "/assets/images/whitebg/btmnav-01.png",
      selectedIconPath: "/assets/images/whitebg/btmnav-01-on.png",
      text: "首页"
    }, 
    {
      pagePath: "/pages/list/index",
      iconPath: "/assets/images/whitebg/btmnav-02.png",
      selectedIconPath: "/assets/images/whitebg/btmnav-02-on.png",
      text: "定义"
    }, 
    {
      pagePath: "/pages/user/index",
      iconPath: "/assets/images/whitebg/btmnav-04.png",
      selectedIconPath: "/assets/images/whitebg/btmnav-04-on.png",
      text: "我的"
    }
  ]
  },
  attached() {
  },
  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
      const query = wx.createSelectorQuery().in(this)
      query.select('.tab-bar').boundingClientRect((rect) => {
        wx.setStorageSync('tabbberHeight', rect.height)
      }).exec()
    },
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({url})
    },
    onChange(ev){
      wx.switchTab({
        url: this.data.list[ev.detail].pagePath
      })
    }
  }
})

index.wxss代码

  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 48px;
  background: white;
  display: flex;
  padding-bottom: env(safe-area-inset-bottom);
  color: #7A7E83;
  color: #3cc51f;
}

.tab-bar-border {
  background-color: #c5c5c554;
  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 .iconPath {
  width: 27px;
  height: 27px;
}

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

index.json代码

{
  "component": true,
  "usingComponents": {
  }
}