index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import baseComponent from '../helpers/baseComponent'
  2. import classNames from '../helpers/classNames'
  3. baseComponent({
  4. properties: {
  5. prefixCls: {
  6. type: String,
  7. value: 'wux-segment',
  8. },
  9. theme: {
  10. type: String,
  11. value: 'balanced',
  12. },
  13. defaultCurrent: {
  14. type: Number,
  15. value: 0,
  16. },
  17. current: {
  18. type: Number,
  19. value: 0,
  20. observer(newVal) {
  21. if (this.data.controlled) {
  22. this.setData({
  23. activeKey: newVal,
  24. })
  25. }
  26. },
  27. },
  28. values: {
  29. type: Array,
  30. value: [],
  31. },
  32. disabled: {
  33. type: Boolean,
  34. value: false,
  35. },
  36. controlled: {
  37. type: Boolean,
  38. value: false,
  39. },
  40. },
  41. data: {
  42. activeKey: 0,
  43. },
  44. computed: {
  45. classes() {
  46. const { prefixCls, theme, disabled } = this.data
  47. const wrap = classNames(prefixCls, {
  48. [`${prefixCls}--${theme}`]: theme,
  49. [`${prefixCls}--disabled`]: disabled,
  50. })
  51. const item = `${prefixCls}__item`
  52. return {
  53. wrap,
  54. item,
  55. }
  56. },
  57. },
  58. methods: {
  59. onTap(e) {
  60. if (this.data.disabled) return
  61. this.setActiveKey(e.currentTarget.dataset.index)
  62. },
  63. emitEvent(key) {
  64. this.triggerEvent('change', {
  65. key,
  66. values: this.data.values,
  67. })
  68. },
  69. setActiveKey(activeKey) {
  70. if (this.data.activeKey !== activeKey) {
  71. if (!this.data.controlled) {
  72. this.setData({
  73. activeKey,
  74. })
  75. }
  76. }
  77. this.emitEvent(activeKey)
  78. },
  79. },
  80. attached() {
  81. const { defaultCurrent, current, controlled } = this.data
  82. const activeKey = controlled ? current : defaultCurrent
  83. if (this.data.activeKey !== activeKey) {
  84. this.setData({
  85. activeKey,
  86. })
  87. }
  88. },
  89. })