Input: fix the issue of incorrect cursor position when updating the value asynchronously.

When updating the value asynchronously, the cursor position is incorrect.
pull/22498/head
Neco86 2023-04-21 14:41:07 +08:00 committed by GitHub
parent f14b5ba540
commit 0c1cd6001e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 0 deletions

View File

@ -113,6 +113,7 @@
import calcTextareaHeight from './calcTextareaHeight'; import calcTextareaHeight from './calcTextareaHeight';
import merge from 'element-ui/src/utils/merge'; import merge from 'element-ui/src/utils/merge';
import {isKorean} from 'element-ui/src/utils/shared'; import {isKorean} from 'element-ui/src/utils/shared';
import {getSelectionInformation, restoreSelection} from './inputSelection';
export default { export default {
name: 'ElInput', name: 'ElInput',
@ -332,6 +333,7 @@
if (!input) return; if (!input) return;
if (input.value === this.nativeInputValue) return; if (input.value === this.nativeInputValue) return;
input.value = this.nativeInputValue; input.value = this.nativeInputValue;
restoreSelection(this.selectionInformation);
}, },
handleFocus(event) { handleFocus(event) {
this.focused = true; this.focused = true;
@ -368,6 +370,8 @@
// ensure native input value is controlled // ensure native input value is controlled
// see: https://github.com/ElemeFE/element/issues/12850 // see: https://github.com/ElemeFE/element/issues/12850
this.$nextTick(this.setNativeInputValue); this.$nextTick(this.setNativeInputValue);
this.selectionInformation = getSelectionInformation(event.target);
}, },
handleChange(event) { handleChange(event) {
this.$emit('change', event.target.value); this.$emit('change', event.target.value);

View File

@ -0,0 +1,38 @@
export function getSelection(input) {
if ('selectionStart' in input) {
return {
start: input.selectionStart,
end: input.selectionEnd
};
}
return null;
}
export function setSelection(input, offsets) {
const start = offsets.start;
let end = offsets.end;
if (end === undefined) {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
}
}
export function getSelectionInformation(input) {
return {
ele: input,
selectionRange: getSelection(input)
};
}
export function restoreSelection(selectionInformation) {
const {ele, selectionRange} = selectionInformation || {};
if (selectionRange) {
setSelection(ele, selectionRange);
}
}