| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496 |
- <template>
- <view
- class="cl-slider"
- :class="[
- {
- 'cl-slider--disabled': disabled
- },
- pt.className
- ]"
- >
- <view
- class="cl-slider__inner"
- :style="{
- height: blockSize + 'rpx'
- }"
- >
- <view
- class="cl-slider__track"
- :class="[pt.track?.className]"
- :style="{
- height: trackHeight + 'rpx'
- }"
- >
- <view class="cl-slider__progress" :style="progressStyle"></view>
- <!-- 单滑块模式 -->
- <view
- v-if="!range"
- class="cl-slider__thumb"
- :class="[pt.thumb?.className]"
- :style="singleThumbStyle"
- ></view>
- <!-- 双滑块模式 -->
- <template v-if="range">
- <view
- class="cl-slider__thumb cl-slider__thumb--min"
- :class="[pt.thumb?.className]"
- :style="minThumbStyle"
- ></view>
- <view
- class="cl-slider__thumb cl-slider__thumb--max"
- :class="[pt.thumb?.className]"
- :style="maxThumbStyle"
- ></view>
- </template>
- </view>
- <view
- class="cl-slider__picker"
- :style="{
- height: blockSize * 1.5 + 'rpx'
- }"
- @touchstart.prevent="onTouchStart"
- @touchmove.prevent="onTouchMove"
- @touchend="onTouchEnd"
- @touchcancel="onTouchEnd"
- ></view>
- </view>
- <cl-text
- v-if="showValue"
- :pt="{
- className: parseClass(['text-center w-[100rpx]', pt.value?.className])
- }"
- >
- {{ displayValue }}
- </cl-text>
- </view>
- </template>
- <script setup lang="ts">
- import { computed, getCurrentInstance, nextTick, onMounted, ref, watch, type PropType } from "vue";
- import { parseClass, parsePt, rpx2px } from "@/cool";
- import type { PassThroughProps } from "../../types";
- defineOptions({
- name: "cl-slider"
- });
- // 组件属性定义
- const props = defineProps({
- // 样式穿透对象
- pt: {
- type: Object,
- default: () => ({})
- },
- // v-model 绑定的值,单值模式使用
- modelValue: {
- type: Number,
- default: 0
- },
- // v-model:values 绑定的值,范围模式使用
- values: {
- type: Array as PropType<number[]>,
- default: () => [0, 0]
- },
- // 最小值
- min: {
- type: Number,
- default: 0
- },
- // 最大值
- max: {
- type: Number,
- default: 100
- },
- // 步长
- step: {
- type: Number,
- default: 1
- },
- // 是否禁用
- disabled: {
- type: Boolean,
- default: false
- },
- // 滑块的大小
- blockSize: {
- type: Number,
- default: 40
- },
- // 线的高度
- trackHeight: {
- type: Number,
- default: 8
- },
- // 是否显示当前值
- showValue: {
- type: Boolean,
- default: false
- },
- // 是否启用范围选择
- range: {
- type: Boolean,
- default: false
- }
- });
- const emit = defineEmits(["update:modelValue", "update:values", "change", "changing"]);
- const { proxy } = getCurrentInstance()!;
- // 样式穿透类型定义
- type PassThrough = {
- className?: string;
- track?: PassThroughProps;
- progress?: PassThroughProps;
- thumb?: PassThroughProps;
- value?: PassThroughProps;
- };
- // 计算样式穿透对象
- const pt = computed(() => parsePt<PassThrough>(props.pt));
- // 当前滑块的值,单值模式
- const value = ref<number>(props.modelValue);
- // 当前范围值,范围模式
- const rangeValue = ref<number[]>([...props.values]);
- // 轨道宽度(像素)
- const trackWidth = ref<number>(0);
- // 轨道左侧距离屏幕的距离(像素)
- const trackLeft = ref<number>(0);
- // 当前活动的滑块索引(0: min, 1: max),仅在范围模式下使用
- const activeThumbIndex = ref<number>(0);
- // 计算当前值的百分比(单值模式)
- const percentage = computed(() => {
- if (props.range) return 0;
- return ((value.value - props.min) / (props.max - props.min)) * 100;
- });
- // 计算范围值的百分比(范围模式)
- type RangePercentage = {
- min: number;
- max: number;
- };
- const rangePercentage = computed<RangePercentage>(() => {
- if (!props.range) return { min: 0, max: 0 };
- const val = rangeValue.value;
- const minPercent = ((val[0] - props.min) / (props.max - props.min)) * 100;
- const maxPercent = ((val[1] - props.min) / (props.max - props.min)) * 100;
- return { min: minPercent, max: maxPercent };
- });
- // 进度条样式
- const progressStyle = computed(() => {
- const style = {};
- if (props.range) {
- const { min, max } = rangePercentage.value;
- style["left"] = `${min}%`;
- style["width"] = `${max - min}%`;
- } else {
- style["width"] = `${percentage.value}%`;
- }
- return style;
- });
- // 创建滑块样式的通用函数
- function createThumbStyle(percent: number) {
- const style = {};
- // 使用像素定位,确保滑块始终在轨道范围内
- const effectiveTrackWidth = trackWidth.value - rpx2px(props.blockSize) + 1;
- const leftPosition = (percent / 100) * effectiveTrackWidth;
- const finalLeft = Math.max(0, Math.min(effectiveTrackWidth, leftPosition));
- style["left"] = `${finalLeft}px`;
- style["width"] = `${rpx2px(props.blockSize)}px`;
- style["height"] = `${rpx2px(props.blockSize)}px`;
- return style;
- }
- // 单滑块样式
- const singleThumbStyle = computed(() => {
- return createThumbStyle(percentage.value);
- });
- // 最小值滑块样式
- const minThumbStyle = computed(() => {
- return createThumbStyle(rangePercentage.value.min);
- });
- // 最大值滑块样式
- const maxThumbStyle = computed(() => {
- return createThumbStyle(rangePercentage.value.max);
- });
- // 显示的值
- const displayValue = computed<string>(() => {
- if (props.range) {
- const val = rangeValue.value;
- return `${val[0]} - ${val[1]}`;
- }
- return `${value.value}`;
- });
- // 获取滑块轨道的宽度和左边距,用于后续触摸计算
- function getTrackInfo(): Promise<void> {
- return new Promise((resolve) => {
- uni.createSelectorQuery()
- .in(proxy)
- .select(".cl-slider__track")
- .boundingClientRect((node) => {
- trackWidth.value = (node as NodeInfo).width ?? 0;
- trackLeft.value = (node as NodeInfo).left ?? 0;
- resolve();
- })
- .exec();
- });
- }
- // 根据触摸点的clientX计算对应的滑块值
- function calculateValue(clientX: number): number {
- // 如果轨道宽度为0,直接返回最小值
- if (trackWidth.value == 0) return props.min;
- // 计算触摸点距离轨道左侧的偏移
- const offset = clientX - trackLeft.value;
- // 计算百分比,限制在0~1之间
- const percentage = Math.max(0, Math.min(1, offset / trackWidth.value));
- // 计算值区间
- const range = props.max - props.min;
- // 计算实际值
- let val = props.min + percentage * range;
- // 按步长取整
- if (props.step > 0) {
- val = Math.round((val - props.min) / props.step) * props.step + props.min;
- }
- // 限制在[min, max]区间
- return Math.max(props.min, Math.min(props.max, val));
- }
- // 在范围模式下,确定应该移动哪个滑块
- function determineActiveThumb(clientX: number) {
- if (!props.range) return 0;
- const val = rangeValue.value;
- const clickValue = calculateValue(clientX);
- // 计算点击位置到两个滑块的距离
- const distToMin = Math.abs(clickValue - val[0]);
- const distToMax = Math.abs(clickValue - val[1]);
- // 选择距离更近的滑块
- return distToMin <= distToMax ? 0 : 1;
- }
- // 更新滑块的值,并触发相应的事件
- function updateValue(val: number | number[]) {
- if (props.range) {
- const newVal = val as number[];
- const oldVal = rangeValue.value;
- // 如果最小值超过了最大值,交换activeThumbIndex
- if (newVal[0] > newVal[1]) {
- activeThumbIndex.value = activeThumbIndex.value == 0 ? 1 : 0;
- }
- // 确保最小值不大于最大值,但允许通过拖动交换角色
- const sortedVal = [Math.min(newVal[0], newVal[1]), Math.max(newVal[0], newVal[1])];
- // 检查值是否真的改变了
- if (JSON.stringify(oldVal) !== JSON.stringify(sortedVal)) {
- rangeValue.value = sortedVal;
- emit("update:values", sortedVal);
- emit("changing", sortedVal);
- }
- } else {
- const newVal = val as number;
- const oldVal = value.value;
- if (oldVal !== newVal) {
- value.value = newVal;
- emit("update:modelValue", newVal);
- emit("changing", newVal);
- }
- }
- }
- // 触摸开始事件,获取轨道信息并初步设置值
- async function onTouchStart(e: TouchEvent) {
- if (props.disabled) return;
- await getTrackInfo();
- nextTick(() => {
- const clientX = e.touches[0].clientX;
- const newValue = calculateValue(clientX);
- if (props.range) {
- activeThumbIndex.value = determineActiveThumb(clientX);
- const val = [...rangeValue.value];
- val[activeThumbIndex.value] = newValue;
- updateValue(val);
- } else {
- updateValue(newValue);
- }
- });
- }
- // 触摸移动事件,实时更新滑块值
- function onTouchMove(e: TouchEvent) {
- if (props.disabled) return;
- const clientX = e.touches[0].clientX;
- const newValue = calculateValue(clientX);
- if (props.range) {
- const val = [...rangeValue.value];
- val[activeThumbIndex.value] = newValue;
- updateValue(val);
- } else {
- updateValue(newValue);
- }
- }
- // 触摸结束事件,触发change事件
- function onTouchEnd() {
- if (props.disabled) return;
- if (props.range) {
- emit("change", rangeValue.value);
- } else {
- emit("change", value.value);
- }
- }
- // 监听外部v-model的变化,保持内部value同步(单值模式)
- watch(
- computed(() => props.modelValue),
- (val: number) => {
- if (val !== value.value) {
- value.value = Math.max(props.min, Math.min(props.max, val));
- }
- },
- { immediate: true }
- );
- // 监听外部v-model:values的变化,保持内部rangeValue同步(范围模式)
- watch(
- computed(() => props.values),
- (val: number[]) => {
- rangeValue.value = val.map((e) => {
- return Math.max(props.min, Math.min(props.max, e));
- });
- },
- { immediate: true }
- );
- // 监听max的变化,确保value不会超过max
- watch(
- computed(() => props.max),
- (val: number) => {
- if (props.range) {
- const rangeVal = rangeValue.value;
- if (rangeVal[0] > val || rangeVal[1] > val) {
- updateValue([Math.min(rangeVal[0], val), Math.min(rangeVal[1], val)]);
- }
- } else {
- const singleVal = value.value;
- if (singleVal > val) {
- updateValue(val);
- }
- }
- },
- { immediate: true }
- );
- // 监听min的变化,确保value不会小于min
- watch(
- computed(() => props.min),
- (val: number) => {
- if (props.range) {
- const rangeVal = rangeValue.value;
- if (rangeVal[0] < val || rangeVal[1] < val) {
- updateValue([Math.max(rangeVal[0], val), Math.max(rangeVal[1], val)]);
- }
- } else {
- const singleVal = value.value;
- if (singleVal < val) {
- updateValue(val);
- }
- }
- },
- { immediate: true }
- );
- onMounted(() => {
- watch(
- computed(() => [props.showValue]),
- () => {
- nextTick(() => {
- getTrackInfo();
- });
- }
- );
- getTrackInfo();
- });
- </script>
- <style lang="scss" scoped>
- .cl-slider {
- @apply flex flex-row items-center w-full overflow-visible;
- &--disabled {
- opacity: 0.6;
- pointer-events: none;
- }
- &__inner {
- @apply flex-1 relative h-full flex flex-row items-center overflow-visible;
- }
- &__picker {
- @apply absolute left-0 w-full;
- }
- &__track {
- @apply relative w-full rounded-full overflow-visible;
- @apply bg-surface-200;
- }
- &__progress {
- @apply absolute top-0 h-full rounded-full;
- @apply bg-primary-400;
- }
- &__thumb {
- @apply absolute top-1/2 rounded-full border border-solid border-white;
- @apply bg-primary-500;
- transform: translateY(-50%);
- pointer-events: none;
- z-index: 1;
- &--min {
- z-index: 2;
- }
- &--max {
- z-index: 2;
- }
- }
- }
- </style>
|