小程序自定义tab-bar,踩坑记录

发布于:2024-12-18 ⋅ 阅读:(194) ⋅ 点赞:(0)

从官方下载代码
https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.html

1、把custom-tab-bar 文件放置 pages同级
修改下 custom-tab-bar 下的 JS文件

Component({
  data: {
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#3cc51f",
    list: [{
      pagePath: "/pages/index/index",
      iconPath: "/static/images/ico/home.png",
      selectedIconPath: "/static/images/ico/home.png",
      text: "A"
    }, {
      pagePath: "/pages/product/product",
      iconPath: "/static/images/ico/home.png",
      selectedIconPath: "/static/images/ico/home.png",
      text: "B"
    },
    {
        pagePath: "/pages/news/news",
        iconPath: "/static/images/ico/home.png",
        selectedIconPath: "/static/images/ico/home.png",
        text: "C"
      },
      {
        pagePath: "/pages/my/my",
        iconPath: "/static/images/ico/home.png",
        selectedIconPath: "/static/images/ico/home.png",
        text: "D"
      },
]
  },
  attached() {
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({url})
    //   this.setData({  这部分注销,到其他页进行赋值
    //     selected: data.index
    //   })
    }
  }
})

2、跳转到指定页面时,在当页面JS上加上代码:

onShow: function () {  //上面注销得部分, 在A-D页面对应上,  A页面=0 ,B=1 以此类推
    if (typeof this.getTabBar === 'function' &&  this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0     //这里的数字设置当前页面在tabbar里对应的序列,从0开始
      })
    }
  }

3、在app.json 开启自定义tab

  "tabBar": {
    "custom": true,  //开启
    "color": "#767676",
    "selectedColor": "#004F8A",
    "backgroundColor": "#fff",
    "borderStyle": "black",
    "list": [

4、在app.js 隐藏原生得JS

// app.js
App({
  onLaunch() {
      wx.hideTabBar(); //隐藏原生得tab bar 
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)


网站公告

今日签到

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