方法一:使用 type="number"
<template><el-input v-model="numberValue" type="number" />
</template><script setup>
import { ref } from 'vue';const numberValue = ref('');
</script>
方法二:使用自定义指令过滤非数字
<template><el-input v-model="numberValue" v-number-onlyplaceholder="只能输入数字"/>
</template><script setup>
import { ref } from 'vue';const numberValue = ref('');// 自定义指令
const vNumberOnly = {mounted(el) {el.querySelector('input').addEventListener('input', (e) => {e.target.value = e.target.value.replace(/[^\d]/g, '');});}
};
</script>
方法三:使用 onInput 事件处理
<template><el-input v-model="numberValue" @input="handleNumberInput"placeholder="只能输入数字"/>
</template><script setup>
import { ref } from 'vue';const numberValue = ref('');const handleNumberInput = (value) => {numberValue.value = value.replace(/[^\d]/g, '');
};
</script>