说明:
使用该组件时焦点在最后,客户要求可更改前面输错信息
实现逻辑
1.获取输入框焦点位置,此次采用的是ref,也可使用document相关
const inputElement = numberKeyboardRef.value;if (inputElement) {cursorPosition.value = inputElement.selectionStart;}
2.监听键盘点击事件
设置焦点位置
numberKeyboardRef.value.setSelectionRange(cursorPosition.value, cursorPosition.value);
更新组件绑定值
emit('update:modelValue', str)
具体代码如下:
<template><input v-model="keyWord" ref="numberKeyboardRef" class="search-input" :autofocus="true" @click="handleSelectionChange"/><van-number-keyboard :show="show":model-value="keyWord":extraKey="extraKey"safe-area-inset-bottom@input="onInput"@delete="onDelete"style="position: static;color: #586C9D":maxlength="18"></van-number-keyboard>
</template>
<script lang="ts" setup>const keyWord = ref('')
const cursorPosition = ref(null)
const numberKeyboardRef = ref()const emit = defineEmits(['update:modelValue'])
const onInput = (v) => {function insertString(originalString, insertString, position) {var firstPart = originalString.substring(0, position);var secondPart = originalString.substring(position);return firstPart + insertString + secondPart;}const str = insertString(keyWord.value, v, cursorPosition.value)emit('update:modelValue',str)keyWord.value = strcursorPosition.value += 1nextTick(() => {numberKeyboardRef.value.setSelectionRange(cursorPosition.value, cursorPosition.value );})
}
const onDelete = () => {if (keyWord.value.length > 0) {cursorPosition.value = cursorPosition.value || keyWord.value.lengthconst str = keyWord.value.slice(0, cursorPosition.value -1) + keyWord.value.slice(cursorPosition.value)emit('update:modelValue', str)keyWord.value = strcursorPosition.value -= 1nextTick(() => {numberKeyboardRef.value.setSelectionRange(cursorPosition.value, cursorPosition.value);})} else {emit('update:modelValue', '')keyWord.value = ''}
}
const handleSelectionChange = (v, e) => {const inputElement = numberKeyboardRef.value;if (inputElement) {cursorPosition.value = inputElement.selectionStart;}
}</script>