Skip to content

Commit

Permalink
fix(Field): incorrect cursor position when using formatter (#11348)
Browse files Browse the repository at this point in the history
  • Loading branch information
chenjiahan committed Dec 2, 2022
1 parent 74d77a6 commit b27a3ce
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions packages/vant/src/field/Field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
}
}

Expand Down

0 comments on commit b27a3ce

Please sign in to comment.