const LIST = [ { pagePath: '/pages/home/home', text: '首页', icon: 'home' }, { pagePath: '/pages/report/report', text: '报告', icon: 'report' }, { pagePath: '/pages/community/community', text: '社区', icon: 'community' }, { pagePath: '/pages/mine/mine', text: '我的', icon: 'user' }, ]; Component({ data: { selected: 0, hidden: false, list: LIST }, lifetimes: { attached() { this.syncSelected(); }, }, methods: { // 高亮由当前页面路径算出来,页面那边不写死 0/1/2/3/4, // 调 tab 顺序只改上面的 LIST 就够了。 // // 触发时机必须由页面 onShow 推(见 utils/tabbar.js):自定义 tabBar 不在 // 页面节点树里,组件自己的 pageLifetimes.show 拿不到可靠时机,实测切到 // 「我的」时高亮还留在「首页」。 syncSelected() { const pages = getCurrentPages(); const cur = pages[pages.length - 1]; if (!cur) return; const i = LIST.findIndex((t) => t.pagePath === '/' + cur.route); if (i >= 0) this.setData({ selected: i }); }, switchTab(e) { wx.switchTab({ url: LIST[e.currentTarget.dataset.index].pagePath }); }, }, });