VUE HTML のテキスト ボックスでは、数字を入力する方法が 2 つしかありません

方法 1、入力イベント + デジタル正規表現

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

 メソッド 2. キーボード キー イベント 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>

おすすめ

転載: blog.csdn.net/lwf3115841/article/details/130496999