switch.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <template>
  2. <view class="s-switch-container">
  3. <view class="s-switch-item" :class="{
  4. 's-switch-selected': item.selected
  5. }"
  6. @click="selectItem(item)"
  7. v-for="item in switchArr" :key="item.key">
  8. {{item.value}}
  9. </view>
  10. </view>
  11. </template>
  12. <script>
  13. export default {
  14. name: 'Switch',
  15. props: {
  16. defaultValue: {
  17. type: Number,
  18. default: 0
  19. },
  20. switchList: {
  21. type: Array,
  22. default: [
  23. {
  24. key: 0,
  25. value: '是'
  26. },
  27. {
  28. key: 1,
  29. value: '否'
  30. }
  31. ]
  32. }
  33. },
  34. data () {
  35. return {
  36. switchArr: []
  37. }
  38. },
  39. methods: {
  40. selectItem (info) {
  41. if (info.selected === false) {
  42. for (const item of this.switchArr) {
  43. if (info.key === item.key) {
  44. item.selected = true
  45. this.$emit('switchValue', item)
  46. } else {
  47. item.selected = false
  48. }
  49. }
  50. }
  51. }
  52. },
  53. created () {
  54. for (let i = 0; i < 2; i++) {
  55. const arrItem = {
  56. key: this.switchList[i].key,
  57. value: this.switchList[i].value,
  58. selected: this.defaultValue === this.switchList[i].key ? true : false
  59. }
  60. if (this.switchList[i].key === this.defaultValue) {
  61. this.$emit('switchValue', arrItem)
  62. }
  63. this.switchArr.push(arrItem)
  64. }
  65. }
  66. }
  67. </script>
  68. <style lang="scss" scoped>
  69. .s-switch-container {
  70. padding: 2upx;
  71. display: flex;
  72. flex-direction: row;
  73. width: 160upx;
  74. height: 60upx;
  75. border-radius: 100upx;
  76. border: 4upx solid #f37b1d;
  77. }
  78. .s-switch-item {
  79. color: #f37b1d;
  80. font-size: 30upx;
  81. width: 80upx;
  82. display: flex;
  83. justify-content: center;
  84. align-items: center;
  85. }
  86. .s-switch-selected {
  87. color: #ffffff;
  88. border-radius: 40upx;
  89. background: #f37b1d;
  90. }
  91. </style>