Vue3 el-input实时转大写、自动去掉空格、光标不跳动

发布时间 2023-05-26 16:35:52作者: WinnieIns

直接上代码:

<script setup>
import {ref,nextTick } from 'vue'
let inputValue = ref(null)
let inputRef = ref(null)
const handleInput = () => {
  
    // 获取光标位置
    const cursorPosition = inputRef.value.input.selectionStart;

    // 转大写并去掉空格
    inputValue.value = inputValue.value.toUpperCase().replace(/\s+/g, "");

    // 设置光标位置
    nextTick(() => {
      inputRef.value.input.setSelectionRange(
        cursorPosition,
        cursorPosition
      );
    });
}
</script>

<template>
  <el-input
    v-model="inputValue"
    @input="handleInput"
    ref="inputRef"
  ></el-input>
</template>