68 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2026-01-30 09:54:26 +08:00
const App = getApp();
2025-08-29 09:51:02 +08:00
Component({
data: {
2026-01-30 09:54:26 +08:00
selected: App.globalData.selectedIndex,
color: "#3D3D3D",
selectedColor: "#3D3D3D",
list: [{
pagePath: "/pages/index/index",
iconPath: "/static/tabbar/home_icon.png",
selectedIconPath: "/static/tabbar/home_active.png",
text: "首页"
}, {
pagePath: "/pages/me/index",
iconPath: "/static/tabbar/news_icon.png",
selectedIconPath: "/static/tabbar/news_active.png",
text: "我的"
},]
},
lifetimes: {
attached: function() {
// 监听路由变化自动更新tab-bar选中状态
const updateTabBar = () => {
let _this = this
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
console.log('currentList', getApp().globalData.menuList)
if (currentPage) {
const currentPath = currentPage.route
const index = this.data.list.findIndex(item => item.pagePath === `/${currentPath}`)
if (index !== -1) {
this.setData({
selected: index,
list: getApp().globalData.menuList
})
App.globalData.selectedIndex = index
}
}
2025-08-29 09:51:02 +08:00
}
2026-01-30 09:54:26 +08:00
// 初始化时执行一次
updateTabBar()
// 注册路由监听
wx.onAppRoute(updateTabBar)
}
},
ready() {
this.setData({
list: getApp().globalData.menuList,
selected: App.globalData.selectedIndex || 0
})
2025-08-29 09:51:02 +08:00
},
methods: {
switchTab(e) {
const data = e.currentTarget.dataset
const url = data.path
2026-01-30 09:54:26 +08:00
App.globalData.selectedIndex = data.index
console.log('App.globalData.selectedIndex', data)
2025-08-29 09:51:02 +08:00
this.setData({
2026-01-30 09:54:26 +08:00
selected: data.index,
list: getApp().globalData.menuList
2025-08-29 09:51:02 +08:00
})
2026-01-30 09:54:26 +08:00
console.log('switchTab fail', url)
wx.switchTab({url, fail: (res) => {
// wx.navigateTo({url})
console.log('switchTab fail', res)
}})
2025-08-29 09:51:02 +08:00
}
}
2026-01-30 09:54:26 +08:00
})