小程序自定义tabbar,以及激活状态闪烁的解决方案

小程序官方代码如下(自定义tabbar组件)

Component({
  data: {
    selected: 0,      //代表当前激活状态
    color: "#7A7E83",
    selectedColor: "#3cc51f",
    list: [{
      pagePath: "/index/index",     //app.json 中定义是index/index,在这里需要在前面加上/:/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    //代表切换激活状态
      })
    }
  }
})

 //小程序tabbar,在路由跳转时,会恢复初始激活状态,所以必须在跳转的页面里加上这样一段代码

//官方写法,会带来一个bug,有时pageLifetimes里的show不会执行
Component({
  pageLifetimes: {
    show() {          //代表父组件页面显示时,子组件执行的方法
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({             
          selected: 0           //将tabbar的值重新设为当前页面需要激活的值
        })
      }
    }
  }
})

  //小程序自定义tabbar完成,按照官方教程,不过,在实际项目中,会出现以下问题,小程序会激活其他tabbar,然后,在激活当前tabbar,可以这样解决,自定义tabbar js修改如下

Component({
  data: {
    selected: '',     //只需要将它的初始激活状态从指定的值设为空,就行
    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
      })
    }
  }
})

  //完美解决,因为小程序路由跳转,tabbar会重新加载一次,就会有初始值,进入一个新的页面时,会先显示初始值,再显示设置的值,就会出现闪烁效果。

  注释:可以在tabbar的switchTab方法中使用全局变量app.globalData存储要跳转的selected值,在自定义tabbar的 attached生命周期中,将selected设置为app.globalData中存储的新路由值,bar切换效果会更好.

原文地址:https://www.cnblogs.com/uimeigui/p/13533097.html