diff --git a/packages/vant/src/slider/Slider.tsx b/packages/vant/src/slider/Slider.tsx index 07a8e715db9..f4be23d9821 100644 --- a/packages/vant/src/slider/Slider.tsx +++ b/packages/vant/src/slider/Slider.tsx @@ -129,8 +129,18 @@ export default defineComponent({ const step = +props.step; value = clamp(value, min, max); + const diff = Math.round((value - min) / step) * step; - return addNumber(min, diff); + const steppedValue = addNumber(min, diff); + + if (steppedValue > max) { + const prevSteppedValue = addNumber(min, diff - step); + const distanceToMax = Math.abs(value - max); + const distanceToPrev = Math.abs(value - prevSteppedValue); + + return distanceToMax <= distanceToPrev ? max : prevSteppedValue; + } + return steppedValue; }; const updateStartValue = () => { diff --git a/packages/vant/src/slider/test/index.spec.ts b/packages/vant/src/slider/test/index.spec.ts index 3ea16b2b987..09733831911 100644 --- a/packages/vant/src/slider/test/index.spec.ts +++ b/packages/vant/src/slider/test/index.spec.ts @@ -374,3 +374,31 @@ test('should update modelValue correctly after clicking the reversed vertical sl trigger(wrapper, 'click', 0, 100); expect(wrapper.emitted('update:modelValue')!.pop()).toEqual([0]); }); + +//https://github.com/youzan/vant/issues/13625 +test('should return max when distanceToMax <= distanceToPrev', () => { + const wrapper = mount(Slider, { + props: { min: 0, max: 50, step: 60, modelValue: 45 }, + }); + + const emitted = wrapper.emitted('update:modelValue'); + if (emitted && emitted.length > 0) { + const result = emitted[emitted.length - 1][0] as number; + expect(result).toBe(50); // Should return max + } +}); + +test('should enter steppedValue > max branch', () => { + const wrapper = mount(Slider, { + props: { min: 0, max: 12, step: 20, modelValue: 0 }, + }); + + wrapper.setProps({ modelValue: 11 }); + + const emitted = wrapper.emitted('update:modelValue'); + if (emitted && emitted.length > 0) { + const result = emitted[emitted.length - 1][0] as number; + expect(result).toBeGreaterThanOrEqual(0); + expect(result).toBeLessThanOrEqual(12); + } +});