The text box in VUE html only allows two ways to enter numbers

Method 1, input event + digital regular expression

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

 Method 2. Keyboard key event 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>

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/130496999