<template>
<a-input v-model:value="num" @input="handInput" />
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
name: "OnlyNum",
props: {},
emits: [],
setup() {
const num = ref("");
function handInput(e) {
num.value = e.target.value.replace(/[^0-9]/g, "");
}
return { num, handInput };
},
});
</script>
<style scoped></style>
方法二、键盘按键事件 keydown
<template>
<a-input v-model:value="num" @keydown="handKeydown" />
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
name: "OnlyNum",
props: {},
emits: [],
setup() {
const num = ref("");
function handKeydown(e) {
let _code = e.keyCode;
// 只允许数字键和删除键
if ((_code >= 48 && _code <= 57) || _code === 8) {
} else {
e.preventDefault();
}
}
return { num, handKeydown };
},
});
</script>
<style scoped></style>