uni-segmented-control.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. <template>
  2. <view
  3. :class="{ text: styleType === 'text' }"
  4. :style="{ borderColor: styleType === 'text' ? '' : activeColor }"
  5. class="segmented-control"
  6. >
  7. <view
  8. v-for="(item, index) in values"
  9. :class="[{ text: styleType === 'text' }, { active: index === currentIndex }]"
  10. :key="index"
  11. :style="{
  12. color:
  13. index === currentIndex
  14. ? styleType === 'text'
  15. ? activeColor
  16. : '#fff'
  17. : styleType === 'text'
  18. ? '#000'
  19. : activeColor,
  20. backgroundColor: index === currentIndex && styleType === 'button' ? activeColor : ''
  21. }"
  22. class="segmented-control-item"
  23. @click="_onClick(index)"
  24. >
  25. {{ item }}
  26. </view>
  27. </view>
  28. </template>
  29. <script>
  30. export default {
  31. name: 'UniSegmentedControl',
  32. props: {
  33. current: {
  34. type: Number,
  35. default: 0
  36. },
  37. values: {
  38. type: Array,
  39. default () {
  40. return []
  41. }
  42. },
  43. activeColor: {
  44. type: String,
  45. default: '#000'
  46. },
  47. styleType: {
  48. type: String,
  49. default: 'button'
  50. }
  51. },
  52. data () {
  53. return {
  54. currentIndex: 0
  55. }
  56. },
  57. watch: {
  58. current (val) {
  59. if (val !== this.currentIndex) {
  60. this.currentIndex = val
  61. }
  62. }
  63. },
  64. created () {
  65. this.currentIndex = this.current
  66. },
  67. methods: {
  68. _onClick (index) {
  69. if (this.currentIndex !== index) {
  70. this.currentIndex = index
  71. this.$emit('clickItem', index)
  72. }
  73. }
  74. }
  75. }
  76. </script>
  77. <style lang="scss">
  78. .segmented-control {
  79. display: flex;
  80. flex-direction: row;
  81. justify-content: center;
  82. width: 75%;
  83. font-size: 28upx;
  84. box-sizing: border-box;
  85. margin: 20px auto;
  86. overflow: hidden;
  87. border: 1px solid;
  88. border-radius: 10upx;
  89. &.text {
  90. border: 0;
  91. border-radius: 0;
  92. }
  93. }
  94. .segmented-control-item {
  95. flex: 1;
  96. text-align: center;
  97. line-height: 60upx;
  98. box-sizing: border-box;
  99. border-left: 1px solid;
  100. &.active {
  101. color: #fff;
  102. }
  103. &.text {
  104. border-left: 0;
  105. color: #000;
  106. &.active {
  107. border-bottom-style: solid;
  108. }
  109. }
  110. &:first-child {
  111. border-left-width: 0;
  112. }
  113. }
  114. </style>