store.ts 2.3 KB

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