const TAB_KEYS = ['nav.home', 'nav.ai', 'nav.message', 'nav.mine'] /** 与 pages.json tabBar.list[].pagePath 一致(无开头 /) */ const TAB_PAGE_PATHS = new Set([ 'pages/home/index', 'pages/ai/index', 'pages/message/index', 'pages/mine/index' ]) /** 运行时会改 TabBar 的 uni API(非 Tab 页调用会报 not TabBar page) */ const TABBAR_API_NAMES = [ 'setTabBarStyle', 'setTabBarItem', 'setTabBarBadge', 'removeTabBarBadge', 'showTabBarRedDot', 'hideTabBarRedDot', 'showTabBar', 'hideTabBar', 'setTabBarMidButton' ] function normalizePageRoute(route) { if (!route) { return '' } let r = String(route).replace(/^\//, '') const prefixes = ['bqH5/', 'bqjy/'] for (const prefix of prefixes) { if (r.startsWith(prefix)) { r = r.slice(prefix.length) } } return r } /** * 当前栈顶是否为原生 TabBar 页 */ export function isTabBarPage() { const stack = getCurrentPages() if (!stack.length) { return false } const cur = stack[stack.length - 1] const route = normalizePageRoute(cur.route || '') return TAB_PAGE_PATHS.has(route) } function installTabBarApiGuard() { if (typeof uni === 'undefined' || !uni.addInterceptor) { return } TABBAR_API_NAMES.forEach((name) => { if (typeof uni[name] !== 'function') { return } uni.addInterceptor(name, { invoke() { if (!isTabBarPage()) { return false } } }) }) } installTabBarApiGuard() /** * 原生 tabBar 的 text 不能写进 pages.json 的 i18n,需在运行时按当前语言更新(仅 Tab 页) * @param {(key: string) => string} t 如 (k) => this.$t(k) */ export function syncTabBarText(t) { if (!isTabBarPage()) { return } TAB_KEYS.forEach((key, index) => { const p = uni.setTabBarItem({ index, text: t(key), fail() {} }) if (p && typeof p.catch === 'function') { p.catch(() => {}) } }) }