天天看点

微信小程序自定义tabbar,切换身份展示不同tabbar

小程序切换身份展示不同tabbar

效果图

微信小程序自定义tabbar,切换身份展示不同tabbar
参考官网给的文档

官网自定义tabbar文档

本方式存在问题— 因为不同身份tabbar不同,用this.getTabBar().setData({list}),导致第一次切换的时候会有一个瞬间的跳动,如果有解决方法,还请不吝赐教------以下正文

app.json中要设置tabbar list
"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": "接口"
      },
      {
        "pagePath": "home/home1/home1",
        "iconPath": "image/icon_component.png",
        "selectedIconPath": "image/icon_component_HL.png",
        "text": "home1"
      },
      {
        "pagePath": "home/home2/home2",
        "iconPath": "image/icon_API.png",
        "selectedIconPath": "image/icon_API_HL.png",
        "text": "home2"
      },
      {
        "pagePath": "home/home3/home3",
        "iconPath": "image/icon_API.png",
        "selectedIconPath": "image/icon_API_HL.png",
        "text": "home3"
      }
    ]
           

引用官网的custom-tab-bar自定义组件修改index.js,删除list

Component({
  data: {
    selected: 0,
    color: "#7A7E83",
    selectedColor: "#3cc51f"
  },
  attached() {
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({url})
      this.setData({
        selected: data.index
      })
    }
  }
})
           

在引用的组件上通过getTabbar().setData()来修改list列表的tabbar item

Component({
  data: {
    index: [{
      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: "接口"
    }]
  },
  pageLifetimes: {
    show() {
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          list: this.data.index,
          selected: 0
        })
      }
    }
  }
})

           

其他组件同理,selected代表当前组件位于list的索引值

参考示例代码

百度网盘链接

提取码:wggw