u-switch.vue 2.2 KB

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