小程序自定義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的值重新設為當前頁面需要激活的值
        })
      }
    }
  }
})
//可以使用一下寫法修復,將Component改為Page,方法寫在onShow里即可
Page({
    onShow: function () {
        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切換效果會更好.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM