const App = getApp(); Component({ data: { 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 } } } // 初始化时执行一次 updateTabBar() // 注册路由监听 wx.onAppRoute(updateTabBar) } }, ready() { this.setData({ list: getApp().globalData.menuList, selected: App.globalData.selectedIndex || 0 }) }, methods: { switchTab(e) { const data = e.currentTarget.dataset const url = data.path App.globalData.selectedIndex = data.index console.log('App.globalData.selectedIndex', data) this.setData({ selected: data.index, list: getApp().globalData.menuList }) console.log('switchTab fail', url) wx.switchTab({url, fail: (res) => { // wx.navigateTo({url}) console.log('switchTab fail', res) }}) } } })