store.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import type { CustomTabBarItem, CustomTabBarItemBadge } from './types'
  2. import { reactive } from 'vue'
  3. import { tabbarList as _tabbarList, customTabbarEnable, selectedTabbarStrategy, TABBAR_STRATEGY_MAP } from './config'
  4. // TODO 1/2: 中间的鼓包tabbarItem的开关
  5. const BULGE_ENABLE = false
  6. /** tabbarList 里面的 path 从 pages.config.ts 得到 */
  7. const tabbarList = reactive<CustomTabBarItem[]>(_tabbarList.map(item => ({
  8. ...item,
  9. pagePath: item.pagePath.startsWith('/') ? item.pagePath : `/${item.pagePath}`,
  10. })))
  11. if (customTabbarEnable && BULGE_ENABLE) {
  12. if (tabbarList.length % 2) {
  13. console.error('有鼓包时 tabbar 数量必须是偶数,否则样式很奇怪!!')
  14. }
  15. tabbarList.splice(tabbarList.length / 2, 0, {
  16. isBulge: true,
  17. } as CustomTabBarItem)
  18. }
  19. export function isPageTabbar(path: string) {
  20. if (selectedTabbarStrategy === TABBAR_STRATEGY_MAP.NO_TABBAR) {
  21. return false
  22. }
  23. const _path = path.split('?')[0]
  24. return tabbarList.some(item => item.pagePath === _path)
  25. }
  26. /**
  27. * 自定义 tabbar 的状态管理,原生 tabbar 无需关注本文件
  28. * tabbar 状态,增加 storageSync 保证刷新浏览器时在正确的 tabbar 页面
  29. * 使用reactive简单状态,而不是 pinia 全局状态
  30. */
  31. const tabbarStore = reactive({
  32. curIdx: uni.getStorageSync('app-tabbar-index') || 0,
  33. prevIdx: uni.getStorageSync('app-tabbar-index') || 0,
  34. setCurIdx(idx: number) {
  35. this.curIdx = idx
  36. uni.setStorageSync('app-tabbar-index', idx)
  37. },
  38. setTabbarItemBadge(idx: number, badge: CustomTabBarItemBadge) {
  39. if (tabbarList[idx]) {
  40. tabbarList[idx].badge = badge
  41. }
  42. },
  43. setAutoCurIdx(path: string) {
  44. // '/' 当做首页
  45. if (path === '/') {
  46. this.setCurIdx(0)
  47. return
  48. }
  49. const index = tabbarList.findIndex(item => item.pagePath === path)
  50. // console.log('tabbarList:', tabbarList)
  51. if (index === -1) {
  52. const pagesPathList = getCurrentPages().map(item => item.route.startsWith('/') ? item.route : `/${item.route}`)
  53. // console.log(pagesPathList)
  54. const flag = tabbarList.some(item => pagesPathList.includes(item.pagePath))
  55. if (!flag) {
  56. this.setCurIdx(0)
  57. return
  58. }
  59. }
  60. else {
  61. this.setCurIdx(index)
  62. }
  63. },
  64. restorePrevIdx() {
  65. if (this.prevIdx === this.curIdx)
  66. return
  67. this.setCurIdx(this.prevIdx)
  68. this.prevIdx = uni.getStorageSync('app-tabbar-index') || 0
  69. },
  70. })
  71. export { tabbarList, tabbarStore }