index.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import baseComponent from '../helpers/baseComponent'
  2. import classNames from '../helpers/classNames'
  3. import { safeAreaInset, checkIPhoneX } from '../helpers/checkIPhoneX'
  4. baseComponent({
  5. relations: {
  6. '../tabbar-item/index': {
  7. type: 'child',
  8. observer() {
  9. this.debounce(this.changeCurrent)
  10. },
  11. },
  12. },
  13. properties: {
  14. prefixCls: {
  15. type: String,
  16. value: 'wux-tabbar',
  17. },
  18. defaultCurrent: {
  19. type: String,
  20. value: '',
  21. },
  22. current: {
  23. type: String,
  24. value: '',
  25. observer: 'changeCurrent',
  26. },
  27. controlled: {
  28. type: Boolean,
  29. value: false,
  30. },
  31. theme: {
  32. type: String,
  33. value: 'balanced',
  34. },
  35. position: {
  36. type: String,
  37. value: '',
  38. },
  39. safeArea: {
  40. type: Boolean,
  41. value: false,
  42. },
  43. },
  44. data: {
  45. tabbarStyle: '',
  46. activeKey: '',
  47. keys: [],
  48. },
  49. computed: {
  50. classes() {
  51. const { prefixCls, position } = this.data
  52. const wrap = classNames(prefixCls, {
  53. [`${prefixCls}--${position}`]: position,
  54. })
  55. return {
  56. wrap,
  57. }
  58. },
  59. },
  60. methods: {
  61. updated(activeKey, condition) {
  62. const elements = this.getRelationNodes('../tabbar-item/index')
  63. if (elements.length > 0) {
  64. if (condition) {
  65. this.setData({
  66. activeKey,
  67. })
  68. elements.forEach((element, index) => {
  69. const key = element.data.key || String(index)
  70. const current = key === activeKey
  71. element.changeCurrent(current, key, this.data.theme, elements.length)
  72. })
  73. }
  74. }
  75. if (this.data.keys.length !== elements.length) {
  76. this.setData({
  77. keys: elements.map((element) => element.data)
  78. })
  79. }
  80. },
  81. changeCurrent(value = this.data.current) {
  82. this.updated(value, this.data.controlled)
  83. },
  84. emitEvent(key) {
  85. this.triggerEvent('change', {
  86. key,
  87. keys: this.data.keys,
  88. })
  89. },
  90. setActiveKey(activeKey) {
  91. if (this.data.activeKey !== activeKey) {
  92. this.updated(activeKey, !this.data.controlled)
  93. }
  94. this.emitEvent(activeKey)
  95. },
  96. applyIPhoneXShim(position = this.data.position) {
  97. if (checkIPhoneX()) {
  98. if (position === 'bottom' || position === 'top') {
  99. this.setData({ tabbarStyle: `${position}: ${safeAreaInset[position]}px` })
  100. }
  101. }
  102. },
  103. },
  104. ready() {
  105. const { defaultCurrent, current, controlled } = this.data
  106. const activeKey = controlled ? current : defaultCurrent
  107. this.updated(activeKey, true)
  108. this.applyIPhoneXShim()
  109. },
  110. })