西藏巴青项目

tabBar.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const TAB_KEYS = ['nav.home', 'nav.ai', 'nav.message', 'nav.mine']
  2. /** 与 pages.json tabBar.list[].pagePath 一致(无开头 /) */
  3. const TAB_PAGE_PATHS = new Set([
  4. 'pages/home/index',
  5. 'pages/ai/index',
  6. 'pages/message/index',
  7. 'pages/mine/index'
  8. ])
  9. /** 运行时会改 TabBar 的 uni API(非 Tab 页调用会报 not TabBar page) */
  10. const TABBAR_API_NAMES = [
  11. 'setTabBarStyle',
  12. 'setTabBarItem',
  13. 'setTabBarBadge',
  14. 'removeTabBarBadge',
  15. 'showTabBarRedDot',
  16. 'hideTabBarRedDot',
  17. 'showTabBar',
  18. 'hideTabBar',
  19. 'setTabBarMidButton'
  20. ]
  21. function normalizePageRoute(route) {
  22. if (!route) {
  23. return ''
  24. }
  25. let r = String(route).replace(/^\//, '')
  26. const prefixes = ['bqH5/', 'bqjy/']
  27. for (const prefix of prefixes) {
  28. if (r.startsWith(prefix)) {
  29. r = r.slice(prefix.length)
  30. }
  31. }
  32. return r
  33. }
  34. /**
  35. * 当前栈顶是否为原生 TabBar 页
  36. */
  37. export function isTabBarPage() {
  38. const stack = getCurrentPages()
  39. if (!stack.length) {
  40. return false
  41. }
  42. const cur = stack[stack.length - 1]
  43. const route = normalizePageRoute(cur.route || '')
  44. return TAB_PAGE_PATHS.has(route)
  45. }
  46. function installTabBarApiGuard() {
  47. if (typeof uni === 'undefined' || !uni.addInterceptor) {
  48. return
  49. }
  50. TABBAR_API_NAMES.forEach((name) => {
  51. if (typeof uni[name] !== 'function') {
  52. return
  53. }
  54. uni.addInterceptor(name, {
  55. invoke() {
  56. if (!isTabBarPage()) {
  57. return false
  58. }
  59. }
  60. })
  61. })
  62. }
  63. installTabBarApiGuard()
  64. /**
  65. * 原生 tabBar 的 text 不能写进 pages.json 的 i18n,需在运行时按当前语言更新(仅 Tab 页)
  66. * @param {(key: string) => string} t 如 (k) => this.$t(k)
  67. */
  68. export function syncTabBarText(t) {
  69. if (!isTabBarPage()) {
  70. return
  71. }
  72. TAB_KEYS.forEach((key, index) => {
  73. const p = uni.setTabBarItem({
  74. index,
  75. text: t(key),
  76. fail() {}
  77. })
  78. if (p && typeof p.catch === 'function') {
  79. p.catch(() => {})
  80. }
  81. })
  82. }