小程序自定义tabbar

发布于:2024-08-17 ⋅ 阅读:(92) ⋅ 点赞:(0)

当前微信开发者工具版本: Stable 1.06.2407110,如果比这个低建议直接用最新版

1.修改app.json,在json中加入如下代码,注意这里的样式和list并不会用到,但是需要存在,而下面的usingComponents里引入的custom-tab-bar则是自定义的tabbar

"tabBar": {
    "custom": true,
    "color": "#000000",
    "selectedColor": "#000000",
    "backgroundColor": "#000000",
    "list": [
      {
        "pagePath": "pages/home/home",
        "text": "首页"
      },
      {
        "pagePath": "pages/my/my",
        "text": "我的"
      }
    ]
  },
  "usingComponents": {
    "custom-tab-bar": "/components/custom-tab-bar/index"
  }

2.在app.json同级目录下自定义custom-tab-bar,文件夹名称必须叫这个custom-tab-bar,这里我用的tdesign组件

custom-tab-bar/index.json:

{
  "component": true,
  "usingComponents": {
    "t-tab-bar": "tdesign-miniprogram/tab-bar/tab-bar",
    "t-tab-bar-item": "tdesign-miniprogram/tab-bar-item/tab-bar-item",
    "t-button": "tdesign-miniprogram/button/button"
  }
}

custom-tab-bar/index.ts:

// custom-tab-bar/index.ts
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    value: '/pages/home/home',
    list: [
      { value: '/pages/home/home', label: '首页', icon: 'home' },
      { value: '/pages/my/my', label: '我的', icon: 'user' },
    ],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 切换页面
    onChange(e: any) {
      console.log(444, e.detail.value)
      this.setData({
        value: e.detail.value,
      });
      wx.switchTab({
        url: e.detail.value,
        success: () => {
          console.log(666)
        }
      })
    },
  }
})

custom-tab-bar/index.wxml:

<!--custom-tab-bar/index.wxml-->
<t-tab-bar t-class="t-tab-bar" value="{{value}}" bindchange="onChange" theme="tag" split="{{false}}">
  <t-tab-bar-item wx:for="{{list}}" wx:key="value" value="{{item.value}}" icon="{{item.icon}}">
    {{item.label}}
  </t-tab-bar-item>
</t-tab-bar>

3.在需要的页面里引入custom-tab-bar组件,注意每个页面都需要引入

首页:pages/home/home.wxml

<!-- 底部tabbar -->
<custom-tab-bar/>

我的:pages/my/my.wxml

<!-- 底部tabbar -->
<custom-tab-bar/>

注:如果底部还存留有原有的tabbar,或者其他奇怪的问题或样式,则关闭微信开发者工具重新进入即可

4.设置切换后高亮

home.ts

// pages/home/home.ts
Page({
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 设置tabbar高亮
    if (typeof this.getTabBar === 'function' ) {
      this.getTabBar().setData({
        value: 0
      })
    }
  },

})

my.ts

// pages/my/my.ts
Page({
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 设置tabbar高亮
    if (typeof this.getTabBar === 'function' ) {
      this.getTabBar().setData({
        value: 1
      })
    }
  },

})

实际效果如下:


网站公告

今日签到

点亮在社区的每一天
去签到