cl-slider.uvue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 class="cl-slider__progress" :style="progressStyle"></view>
  25. <!-- 单滑块模式 -->
  26. <view
  27. v-if="!range"
  28. class="cl-slider__thumb"
  29. :class="[pt.thumb?.className]"
  30. :style="singleThumbStyle"
  31. ></view>
  32. <!-- 双滑块模式 -->
  33. <template v-if="range">
  34. <view
  35. class="cl-slider__thumb cl-slider__thumb--min"
  36. :class="[pt.thumb?.className]"
  37. :style="minThumbStyle"
  38. ></view>
  39. <view
  40. class="cl-slider__thumb cl-slider__thumb--max"
  41. :class="[pt.thumb?.className]"
  42. :style="maxThumbStyle"
  43. ></view>
  44. </template>
  45. </view>
  46. <view
  47. class="cl-slider__picker"
  48. :style="{
  49. height: blockSize * 1.5 + 'rpx'
  50. }"
  51. @touchstart.prevent="onTouchStart"
  52. @touchmove.prevent="onTouchMove"
  53. @touchend="onTouchEnd"
  54. @touchcancel="onTouchEnd"
  55. ></view>
  56. </view>
  57. <cl-text
  58. v-if="showValue"
  59. :pt="{
  60. className: parseClass(['text-center w-[100rpx]', pt.value?.className])
  61. }"
  62. >
  63. {{ displayValue }}
  64. </cl-text>
  65. </view>
  66. </template>
  67. <script setup lang="ts">
  68. import { computed, getCurrentInstance, nextTick, onMounted, ref, watch, type PropType } from "vue";
  69. import { parseClass, parsePt, rpx2px } from "@/cool";
  70. import type { PassThroughProps } from "../../types";
  71. defineOptions({
  72. name: "cl-slider"
  73. });
  74. // 组件属性定义
  75. const props = defineProps({
  76. // 样式穿透对象
  77. pt: {
  78. type: Object,
  79. default: () => ({})
  80. },
  81. // v-model 绑定的值,单值模式使用
  82. modelValue: {
  83. type: Number,
  84. default: 0
  85. },
  86. // v-model:values 绑定的值,范围模式使用
  87. values: {
  88. type: Array as PropType<number[]>,
  89. default: () => [0, 0]
  90. },
  91. // 最小值
  92. min: {
  93. type: Number,
  94. default: 0
  95. },
  96. // 最大值
  97. max: {
  98. type: Number,
  99. default: 100
  100. },
  101. // 步长
  102. step: {
  103. type: Number,
  104. default: 1
  105. },
  106. // 是否禁用
  107. disabled: {
  108. type: Boolean,
  109. default: false
  110. },
  111. // 滑块的大小
  112. blockSize: {
  113. type: Number,
  114. default: 40
  115. },
  116. // 线的高度
  117. trackHeight: {
  118. type: Number,
  119. default: 8
  120. },
  121. // 是否显示当前值
  122. showValue: {
  123. type: Boolean,
  124. default: false
  125. },
  126. // 是否启用范围选择
  127. range: {
  128. type: Boolean,
  129. default: false
  130. }
  131. });
  132. const emit = defineEmits(["update:modelValue", "update:values", "change", "changing"]);
  133. const { proxy } = getCurrentInstance()!;
  134. // 样式穿透类型定义
  135. type PassThrough = {
  136. className?: string;
  137. track?: PassThroughProps;
  138. progress?: PassThroughProps;
  139. thumb?: PassThroughProps;
  140. value?: PassThroughProps;
  141. };
  142. // 计算样式穿透对象
  143. const pt = computed(() => parsePt<PassThrough>(props.pt));
  144. // 当前滑块的值,单值模式
  145. const value = ref<number>(props.modelValue);
  146. // 当前范围值,范围模式
  147. const rangeValue = ref<number[]>([...props.values]);
  148. // 轨道宽度(像素)
  149. const trackWidth = ref<number>(0);
  150. // 轨道左侧距离屏幕的距离(像素)
  151. const trackLeft = ref<number>(0);
  152. // 当前活动的滑块索引(0: min, 1: max),仅在范围模式下使用
  153. const activeThumbIndex = ref<number>(0);
  154. // 计算当前值的百分比(单值模式)
  155. const percentage = computed(() => {
  156. if (props.range) return 0;
  157. return ((value.value - props.min) / (props.max - props.min)) * 100;
  158. });
  159. // 计算范围值的百分比(范围模式)
  160. type RangePercentage = {
  161. min: number;
  162. max: number;
  163. };
  164. const rangePercentage = computed<RangePercentage>(() => {
  165. if (!props.range) return { min: 0, max: 0 };
  166. const val = rangeValue.value;
  167. const minPercent = ((val[0] - props.min) / (props.max - props.min)) * 100;
  168. const maxPercent = ((val[1] - props.min) / (props.max - props.min)) * 100;
  169. return { min: minPercent, max: maxPercent };
  170. });
  171. // 进度条样式
  172. const progressStyle = computed(() => {
  173. const style = {};
  174. if (props.range) {
  175. const { min, max } = rangePercentage.value;
  176. style["left"] = `${min}%`;
  177. style["width"] = `${max - min}%`;
  178. } else {
  179. style["width"] = `${percentage.value}%`;
  180. }
  181. return style;
  182. });
  183. // 创建滑块样式的通用函数
  184. function createThumbStyle(percent: number) {
  185. const style = {};
  186. // 使用像素定位,确保滑块始终在轨道范围内
  187. const effectiveTrackWidth = trackWidth.value - rpx2px(props.blockSize) + 1;
  188. const leftPosition = (percent / 100) * effectiveTrackWidth;
  189. const finalLeft = Math.max(0, Math.min(effectiveTrackWidth, leftPosition));
  190. style["left"] = `${finalLeft}px`;
  191. style["width"] = `${rpx2px(props.blockSize)}px`;
  192. style["height"] = `${rpx2px(props.blockSize)}px`;
  193. return style;
  194. }
  195. // 单滑块样式
  196. const singleThumbStyle = computed(() => {
  197. return createThumbStyle(percentage.value);
  198. });
  199. // 最小值滑块样式
  200. const minThumbStyle = computed(() => {
  201. return createThumbStyle(rangePercentage.value.min);
  202. });
  203. // 最大值滑块样式
  204. const maxThumbStyle = computed(() => {
  205. return createThumbStyle(rangePercentage.value.max);
  206. });
  207. // 显示的值
  208. const displayValue = computed<string>(() => {
  209. if (props.range) {
  210. const val = rangeValue.value;
  211. return `${val[0]} - ${val[1]}`;
  212. }
  213. return `${value.value}`;
  214. });
  215. // 获取滑块轨道的宽度和左边距,用于后续触摸计算
  216. function getTrackInfo(): Promise<void> {
  217. return new Promise((resolve) => {
  218. uni.createSelectorQuery()
  219. .in(proxy)
  220. .select(".cl-slider__track")
  221. .boundingClientRect((node) => {
  222. trackWidth.value = (node as NodeInfo).width ?? 0;
  223. trackLeft.value = (node as NodeInfo).left ?? 0;
  224. resolve();
  225. })
  226. .exec();
  227. });
  228. }
  229. // 根据触摸点的clientX计算对应的滑块值
  230. function calculateValue(clientX: number): number {
  231. // 如果轨道宽度为0,直接返回最小值
  232. if (trackWidth.value == 0) return props.min;
  233. // 计算触摸点距离轨道左侧的偏移
  234. const offset = clientX - trackLeft.value;
  235. // 计算百分比,限制在0~1之间
  236. const percentage = Math.max(0, Math.min(1, offset / trackWidth.value));
  237. // 计算值区间
  238. const range = props.max - props.min;
  239. // 计算实际值
  240. let val = props.min + percentage * range;
  241. // 按步长取整
  242. if (props.step > 0) {
  243. val = Math.round((val - props.min) / props.step) * props.step + props.min;
  244. }
  245. // 限制在[min, max]区间
  246. return Math.max(props.min, Math.min(props.max, val));
  247. }
  248. // 在范围模式下,确定应该移动哪个滑块
  249. function determineActiveThumb(clientX: number) {
  250. if (!props.range) return 0;
  251. const val = rangeValue.value;
  252. const clickValue = calculateValue(clientX);
  253. // 计算点击位置到两个滑块的距离
  254. const distToMin = Math.abs(clickValue - val[0]);
  255. const distToMax = Math.abs(clickValue - val[1]);
  256. // 选择距离更近的滑块
  257. return distToMin <= distToMax ? 0 : 1;
  258. }
  259. // 更新滑块的值,并触发相应的事件
  260. function updateValue(val: number | number[]) {
  261. if (props.range) {
  262. const newVal = val as number[];
  263. const oldVal = rangeValue.value;
  264. // 如果最小值超过了最大值,交换activeThumbIndex
  265. if (newVal[0] > newVal[1]) {
  266. activeThumbIndex.value = activeThumbIndex.value == 0 ? 1 : 0;
  267. }
  268. // 确保最小值不大于最大值,但允许通过拖动交换角色
  269. const sortedVal = [Math.min(newVal[0], newVal[1]), Math.max(newVal[0], newVal[1])];
  270. // 检查值是否真的改变了
  271. if (JSON.stringify(oldVal) !== JSON.stringify(sortedVal)) {
  272. rangeValue.value = sortedVal;
  273. emit("update:values", sortedVal);
  274. emit("changing", sortedVal);
  275. }
  276. } else {
  277. const newVal = val as number;
  278. const oldVal = value.value;
  279. if (oldVal !== newVal) {
  280. value.value = newVal;
  281. emit("update:modelValue", newVal);
  282. emit("changing", newVal);
  283. }
  284. }
  285. }
  286. // 触摸开始事件,获取轨道信息并初步设置值
  287. async function onTouchStart(e: TouchEvent) {
  288. if (props.disabled) return;
  289. await getTrackInfo();
  290. nextTick(() => {
  291. const clientX = e.touches[0].clientX;
  292. const newValue = calculateValue(clientX);
  293. if (props.range) {
  294. activeThumbIndex.value = determineActiveThumb(clientX);
  295. const val = [...rangeValue.value];
  296. val[activeThumbIndex.value] = newValue;
  297. updateValue(val);
  298. } else {
  299. updateValue(newValue);
  300. }
  301. });
  302. }
  303. // 触摸移动事件,实时更新滑块值
  304. function onTouchMove(e: TouchEvent) {
  305. if (props.disabled) return;
  306. const clientX = e.touches[0].clientX;
  307. const newValue = calculateValue(clientX);
  308. if (props.range) {
  309. const val = [...rangeValue.value];
  310. val[activeThumbIndex.value] = newValue;
  311. updateValue(val);
  312. } else {
  313. updateValue(newValue);
  314. }
  315. }
  316. // 触摸结束事件,触发change事件
  317. function onTouchEnd() {
  318. if (props.disabled) return;
  319. if (props.range) {
  320. emit("change", rangeValue.value);
  321. } else {
  322. emit("change", value.value);
  323. }
  324. }
  325. // 监听外部v-model的变化,保持内部value同步(单值模式)
  326. watch(
  327. computed(() => props.modelValue),
  328. (val: number) => {
  329. if (val !== value.value) {
  330. value.value = Math.max(props.min, Math.min(props.max, val));
  331. }
  332. },
  333. { immediate: true }
  334. );
  335. // 监听外部v-model:values的变化,保持内部rangeValue同步(范围模式)
  336. watch(
  337. computed(() => props.values),
  338. (val: number[]) => {
  339. rangeValue.value = val.map((e) => {
  340. return Math.max(props.min, Math.min(props.max, e));
  341. });
  342. },
  343. { immediate: true }
  344. );
  345. // 监听max的变化,确保value不会超过max
  346. watch(
  347. computed(() => props.max),
  348. (val: number) => {
  349. if (props.range) {
  350. const rangeVal = rangeValue.value;
  351. if (rangeVal[0] > val || rangeVal[1] > val) {
  352. updateValue([Math.min(rangeVal[0], val), Math.min(rangeVal[1], val)]);
  353. }
  354. } else {
  355. const singleVal = value.value;
  356. if (singleVal > val) {
  357. updateValue(val);
  358. }
  359. }
  360. },
  361. { immediate: true }
  362. );
  363. // 监听min的变化,确保value不会小于min
  364. watch(
  365. computed(() => props.min),
  366. (val: number) => {
  367. if (props.range) {
  368. const rangeVal = rangeValue.value;
  369. if (rangeVal[0] < val || rangeVal[1] < val) {
  370. updateValue([Math.max(rangeVal[0], val), Math.max(rangeVal[1], val)]);
  371. }
  372. } else {
  373. const singleVal = value.value;
  374. if (singleVal < val) {
  375. updateValue(val);
  376. }
  377. }
  378. },
  379. { immediate: true }
  380. );
  381. onMounted(() => {
  382. watch(
  383. computed(() => [props.showValue]),
  384. () => {
  385. nextTick(() => {
  386. getTrackInfo();
  387. });
  388. }
  389. );
  390. getTrackInfo();
  391. });
  392. </script>
  393. <style lang="scss" scoped>
  394. .cl-slider {
  395. @apply flex flex-row items-center w-full overflow-visible;
  396. &--disabled {
  397. opacity: 0.6;
  398. pointer-events: none;
  399. }
  400. &__inner {
  401. @apply flex-1 relative h-full flex flex-row items-center overflow-visible;
  402. }
  403. &__picker {
  404. @apply absolute left-0 w-full;
  405. }
  406. &__track {
  407. @apply relative w-full rounded-full overflow-visible;
  408. @apply bg-surface-200;
  409. }
  410. &__progress {
  411. @apply absolute top-0 h-full rounded-full;
  412. @apply bg-primary-400;
  413. }
  414. &__thumb {
  415. @apply absolute top-1/2 rounded-full border border-solid border-white;
  416. @apply bg-primary-500;
  417. transform: translateY(-50%);
  418. pointer-events: none;
  419. z-index: 1;
  420. &--min {
  421. z-index: 2;
  422. }
  423. &--max {
  424. z-index: 2;
  425. }
  426. }
  427. }
  428. </style>