cl-slider.uvue 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. <template>
  2. <view
  3. class="cl-slider"
  4. :class="[
  5. {
  6. 'cl-slider--disabled': disabled
  7. },
  8. pt.className
  9. ]"
  10. >
  11. <view
  12. class="cl-slider__inner"
  13. :style="{
  14. height: blockSize + 'px'
  15. }"
  16. >
  17. <view class="cl-slider__track" :class="[pt.track?.className]">
  18. <view
  19. class="cl-slider__progress"
  20. :style="{
  21. width: percentage + '%'
  22. }"
  23. ></view>
  24. <view class="cl-slider__thumb" :class="[pt.thumb?.className]" :style="thumbStyle">
  25. </view>
  26. </view>
  27. <view
  28. class="cl-slider__picker"
  29. :style="{
  30. height: blockSize * 1.5 + 'px'
  31. }"
  32. @touchstart="onTouchStart"
  33. @touchmove="onTouchMove"
  34. @touchend="onTouchEnd"
  35. @touchcancel="onTouchEnd"
  36. ></view>
  37. </view>
  38. <cl-text
  39. v-if="showValue"
  40. :pt="{
  41. className: parseClass(['text-center w-[100rpx]', pt.value?.className])
  42. }"
  43. >
  44. {{ value }}
  45. </cl-text>
  46. </view>
  47. </template>
  48. <script setup lang="ts">
  49. import { computed, getCurrentInstance, nextTick, onMounted, ref, watch } from "vue";
  50. import { parseClass, parsePt } from "@/cool";
  51. import type { PassThroughProps } from "../../types";
  52. defineOptions({
  53. name: "cl-slider"
  54. });
  55. // 组件属性定义
  56. const props = defineProps({
  57. // 样式穿透对象
  58. pt: {
  59. type: Object,
  60. default: () => ({})
  61. },
  62. // v-model 绑定的值
  63. modelValue: {
  64. type: Number,
  65. default: 0
  66. },
  67. // 最小值
  68. min: {
  69. type: Number,
  70. default: 0
  71. },
  72. // 最大值
  73. max: {
  74. type: Number,
  75. default: 100
  76. },
  77. // 步长
  78. step: {
  79. type: Number,
  80. default: 1
  81. },
  82. // 是否禁用
  83. disabled: {
  84. type: Boolean,
  85. default: false
  86. },
  87. // 滑块的大小(px)
  88. blockSize: {
  89. type: Number,
  90. default: 20
  91. },
  92. // 是否显示当前值
  93. showValue: {
  94. type: Boolean,
  95. default: false
  96. }
  97. });
  98. const emit = defineEmits(["update:modelValue", "change", "changing"]);
  99. const { proxy } = getCurrentInstance()!;
  100. // 样式穿透类型定义
  101. type PassThrough = {
  102. className?: string;
  103. track?: PassThroughProps;
  104. progress?: PassThroughProps;
  105. thumb?: PassThroughProps;
  106. value?: PassThroughProps;
  107. };
  108. // 计算样式穿透对象
  109. const pt = computed(() => parsePt<PassThrough>(props.pt));
  110. // 当前滑块的值,受控于v-model
  111. const value = ref<number>(props.modelValue);
  112. // 轨道宽度(像素)
  113. const trackWidth = ref<number>(0);
  114. // 轨道左侧距离屏幕的距离(像素)
  115. const trackLeft = ref<number>(0);
  116. // 计算当前值在[min, max]区间内的百分比
  117. const percentage = computed(() => {
  118. // 公式:(当前值 - 最小值) / (最大值 - 最小值) * 100
  119. // 结果为0~100之间的百分比
  120. return ((value.value - props.min) / (props.max - props.min)) * 100;
  121. });
  122. // 计算滑块thumb的样式
  123. const thumbStyle = computed(() => {
  124. const style = new Map<string, string>();
  125. // 如果轨道宽度还没获取到,先用百分比定位
  126. if (trackWidth.value == 0) {
  127. style.set("left", `${percentage.value}%`);
  128. style.set("width", `${props.blockSize}px`);
  129. style.set("height", `${props.blockSize}px`);
  130. style.set("transform", `translateX(-50%)`);
  131. }
  132. // 使用像素定位,确保滑块始终在轨道范围内
  133. // 可滑动的有效区域 = 轨道宽度 - 滑块宽度
  134. const effectiveTrackWidth = trackWidth.value - props.blockSize;
  135. // 滑块左边距 = 百分比 * 有效轨道宽度
  136. const leftPosition = (percentage.value / 100) * effectiveTrackWidth;
  137. // 限制在有效范围内
  138. const finalLeft = Math.max(0, Math.min(effectiveTrackWidth, leftPosition));
  139. // 返回样式对象,使用像素定位
  140. style.set("left", `${finalLeft}px`);
  141. style.set("width", `${props.blockSize}px`);
  142. style.set("height", `${props.blockSize}px`);
  143. return style;
  144. });
  145. // 获取滑块轨道的宽度和左边距,用于后续触摸计算
  146. function getTrackInfo() {
  147. uni.createSelectorQuery()
  148. .in(proxy)
  149. .select(".cl-slider__track")
  150. .boundingClientRect((node) => {
  151. trackWidth.value = (node as NodeInfo).width ?? 0;
  152. trackLeft.value = (node as NodeInfo).left ?? 0;
  153. })
  154. .exec();
  155. }
  156. // 根据触摸点的clientX计算对应的滑块值
  157. function calculateValue(clientX: number): number {
  158. // 如果轨道宽度为0,直接返回当前值
  159. if (trackWidth.value == 0) return value.value;
  160. // 计算触摸点距离轨道左侧的偏移
  161. const offset = clientX - trackLeft.value;
  162. // 计算百分比,限制在0~1之间
  163. const percentage = Math.max(0, Math.min(1, offset / trackWidth.value));
  164. // 计算值区间
  165. const range = props.max - props.min;
  166. // 计算实际值
  167. let val = props.min + percentage * range;
  168. // 按步长取整
  169. if (props.step > 0) {
  170. val = Math.round((val - props.min) / props.step) * props.step + props.min;
  171. }
  172. // 限制在[min, max]区间
  173. return Math.max(props.min, Math.min(props.max, val));
  174. }
  175. // 更新滑块的值,并触发v-model和changing事件
  176. function updateValue(val: number) {
  177. if (val !== value.value) {
  178. value.value = val;
  179. emit("update:modelValue", val);
  180. emit("changing", val);
  181. }
  182. }
  183. // 触摸开始事件,获取轨道信息并初步设置值
  184. function onTouchStart(e: UniTouchEvent) {
  185. if (props.disabled) return;
  186. getTrackInfo();
  187. // 延迟10ms,确保轨道信息已获取
  188. setTimeout(() => {
  189. const clientX = e.touches[0].clientX;
  190. const value = calculateValue(clientX);
  191. updateValue(value);
  192. }, 10);
  193. }
  194. // 触摸移动事件,实时更新滑块值
  195. function onTouchMove(e: UniTouchEvent) {
  196. if (props.disabled) return;
  197. e.preventDefault();
  198. const clientX = e.touches[0].clientX;
  199. const value = calculateValue(clientX);
  200. updateValue(value);
  201. }
  202. // 触摸结束事件,触发change事件
  203. function onTouchEnd() {
  204. if (props.disabled) return;
  205. emit("change", value.value);
  206. }
  207. // 监听外部v-model的变化,保持内部value同步
  208. watch(
  209. computed(() => props.modelValue),
  210. (val: number) => {
  211. if (val !== value.value) {
  212. // 限制同步值在[min, max]区间
  213. value.value = Math.max(props.min, Math.min(props.max, val));
  214. }
  215. },
  216. { immediate: true }
  217. );
  218. // 监听max的变化,确保value不会超过max
  219. watch(
  220. computed(() => props.max),
  221. (val: number) => {
  222. if (value.value > val) {
  223. updateValue(val);
  224. }
  225. },
  226. {
  227. immediate: true
  228. }
  229. );
  230. // 监听min的变化,确保value不会小于min
  231. watch(
  232. computed(() => props.min),
  233. (val: number) => {
  234. if (value.value < val) {
  235. updateValue(val);
  236. }
  237. },
  238. {
  239. immediate: true
  240. }
  241. );
  242. watch(
  243. computed(() => props.showValue),
  244. () => {
  245. nextTick(() => {
  246. getTrackInfo();
  247. });
  248. }
  249. );
  250. onMounted(() => {
  251. getTrackInfo();
  252. });
  253. </script>
  254. <style lang="scss" scoped>
  255. .cl-slider {
  256. @apply flex flex-row items-center w-full;
  257. overflow: visible;
  258. &--disabled {
  259. opacity: 0.6;
  260. pointer-events: none;
  261. }
  262. &__inner {
  263. @apply flex-1 relative h-full flex flex-row items-center;
  264. overflow: visible;
  265. }
  266. &__picker {
  267. @apply absolute left-0 w-full;
  268. }
  269. &__track {
  270. @apply relative w-full rounded-full;
  271. @apply bg-surface-200;
  272. height: 8rpx;
  273. overflow: visible;
  274. }
  275. &__progress {
  276. @apply absolute top-0 left-0 h-full rounded-full;
  277. @apply bg-primary-400;
  278. }
  279. &__thumb {
  280. @apply absolute top-1/2 rounded-full border border-solid border-white;
  281. @apply bg-primary-500;
  282. transform: translateY(-50%);
  283. pointer-events: none;
  284. }
  285. }
  286. </style>