cl-slider.uvue 7.0 KB

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