小程式自定義tabbar,以及啟用狀態閃爍的解決方案
阿新 • • 發佈:2020-08-20
小程式官方程式碼如下(自定義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,在路由跳轉時,會恢復初始啟用狀態,所以必須在跳轉的頁面里加上這樣一段程式碼
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切換效果會更好.