During project development, I found that el-input-number can enter a strange combination of 10+ or -10+, causing the value to become null when submitted.
The solution is to use keydown.
<template>
<el-input-number v-model="num" :min="1" :max="10"
@change="handleChange" @keydown="onKeydown" />
</template>
<script lang="ts" setup>
import { ref } from 'vue'
const num = ref(1)
const handleChange = (value: number) => {
console.log(value)
}
const onKeydown = (e)=>{
// 输入框中禁止输入e、+、-
let key = e.key;
if (key === 'e' || key === 'E' || key === '+' || key === '-') {
e.returnValue = false;
} else {
e.returnValue = true;
}
}
</script>
Advanced usage becomes custom instructions
First create a TiMiInputNumber.ts file in the utils folder
import { Directive } from 'vue';
export const TimiKeydown: Directive = {
mounted(el, binding) {
function handleKeydown(e: KeyboardEvent) {
// 输入框中禁止输入e、+、-
let key = e.key;
if (key === 'e' || key === 'E' || key === '+' || key === '-') {
e.preventDefault();
}
}
el.addEventListener('keydown', handleKeydown);
},
// unmounted(el) {
// el.removeEventListener('keydown', handleKeydown);
// }
};
Register references globally in main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { TimiKeydown } from './utils/TiMiInputNumber.ts';
const app = createApp(App);
app.directive('timi-keydown', TimiKeydown);
app.mount('#app');
Scenario usage adds v-timi-keydown
<el-input-number
v-model="form.n_Sort"
class="mx-4"
:min="1"
v-timi-keydown
controls-position="right"
/>