1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > VUE html里的文本框只允许输入数字的两种方法

VUE html里的文本框只允许输入数字的两种方法

时间:2021-11-07 00:48:52

相关推荐

VUE html里的文本框只允许输入数字的两种方法

方法一、input 事件 + 数字正则表达式

<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>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。