From b27a3cedfe53356e381c9cc3b53ab554072fda37 Mon Sep 17 00:00:00 2001 From: neverland Date: Fri, 2 Dec 2022 19:17:45 +0800 Subject: [PATCH] fix(Field): incorrect cursor position when using formatter (#11348) --- packages/vant/src/field/Field.tsx | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/vant/src/field/Field.tsx b/packages/vant/src/field/Field.tsx index d2f617f70..caa2be170 100644 --- a/packages/vant/src/field/Field.tsx +++ b/packages/vant/src/field/Field.tsx @@ -291,7 +291,9 @@ export default defineComponent({ value: string, trigger: FieldFormatTrigger = 'onChange' ) => { + const originalValue = value; value = limitValueLength(value); + const isExceedLimit = value !== originalValue; if (props.type === 'number' || props.type === 'digit') { const isNumber = props.type === 'number'; @@ -303,10 +305,18 @@ export default defineComponent({ } if (inputRef.value && inputRef.value.value !== value) { - const { selectionStart, selectionEnd } = inputRef.value; - inputRef.value.value = value; - if (state.focused) { - inputRef.value.setSelectionRange(selectionStart, selectionEnd); + // When the value length exceeds maxlength and the input is focused, + // correct the cursor position to be consistent with the native behavior. + // https://github.com/youzan/vant/issues/11289 + if (state.focused && isExceedLimit) { + const { selectionStart, selectionEnd } = inputRef.value; + inputRef.value.value = value; + inputRef.value.setSelectionRange( + selectionStart! - 1, + selectionEnd! - 1 + ); + } else { + inputRef.value.value = value; } }