u-switch.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <template>
  2. <view class="container" @click="toggleSwitch">
  3. <view :class="['switch', isOn ? 'switch-checked' : 'switch-nochecked']">
  4. <!-- background handled by switch itself -->
  5. <view class="switch-handle" :style="isOn ? 'left: 0;' : 'right: 0;'"></view>
  6. <text class="iconText" v-if="isOn">{{ activeText }}</text>
  7. <text class="iconText" v-else>{{ inactiveText }}</text>
  8. </view>
  9. </view>
  10. </template>
  11. <script setup>
  12. import {
  13. ref,
  14. watch,
  15. } from 'vue';
  16. const props = defineProps({
  17. value: {
  18. type: Boolean,
  19. default: false
  20. },
  21. activeText: {
  22. type: String,
  23. default: '已上线'
  24. },
  25. inactiveText: {
  26. type: String,
  27. default: '已下线'
  28. },
  29. activeValue: {
  30. type: [Number,
  31. String,
  32. Boolean
  33. ],
  34. default: true
  35. },
  36. inactiveValue: {
  37. type: [Number,
  38. String,
  39. Boolean
  40. ],
  41. default: false
  42. },
  43. });
  44. const emit = defineEmits(['update:value', 'change']);
  45. const isOn = ref(props.value);
  46. // keep `isOn` in sync when prop changes using watchEffect to avoid
  47. // generics/return-type confusion in UTS.
  48. watchEffect(() => {
  49. const v = props.value;
  50. if (v != null) {
  51. isOn.value = v as boolean;
  52. }
  53. });
  54. const toggleSwitch = () => {
  55. isOn.value = !isOn.value;
  56. emit('update:value', isOn.value ? props.activeValue : props.inactiveValue);
  57. emit('change', isOn.value ? props.activeValue : props.inactiveValue);
  58. };
  59. </script>
  60. <style lang="scss" scoped>
  61. .container {
  62. width: 156rpx;
  63. }
  64. .switch {
  65. position: relative;
  66. width: 156rpx;
  67. /* match container */
  68. height: 50rpx;
  69. border-radius: 40rpx;
  70. background-color: #d5d5d5;
  71. transition: background-color 0.3s ease;
  72. text-align: center;
  73. align-items: center;
  74. justify-content: center;
  75. }
  76. .switch-handle {
  77. position: absolute;
  78. top: 3rpx;
  79. // left: 3rpx;
  80. width: 44rpx;
  81. height: 44rpx;
  82. border-radius: 22rpx;
  83. /* half of 44rpx handle to make it circular */
  84. background: #fff;
  85. border: 2rpx solid #e0e0e0;
  86. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
  87. transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  88. }
  89. .switch-checked {
  90. background-color: #ffda59;
  91. }
  92. .switch-nochecked {
  93. background-color: #d5d5d5;
  94. }
  95. .switch-checked .switch-handle {
  96. left: 109rpx;
  97. /* moved to other side */
  98. }
  99. .iconText {
  100. font-size: 28rpx
  101. }
  102. </style>