HTML input 只允许输入数字

HTML input 只允许输入数字

方法一、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>
posted @ 2023-04-21 18:34  飞仔FeiZai  阅读(534)  评论(0编辑  收藏  举报