如何限制vue输入中的位数?

sin*_*Gob 4 javascript vue.js

我的目标是限制用户可以在输入字段中输入的数字数量。所以一个用户只能输入 10 位数字。我试过 min 和 max 仍然不起作用

这是代码

        <input
          v-model="amount"
          type="number"
        >


        <script>
             export default {
                  data() {
                      return { 
                          amount: 7800
                      }
                   }

              }

        </script>
Run Code Online (Sandbox Code Playgroud)

现在我可以添加超过 10 位数字

Ama*_*rat 20

替换这个:

<input v-model="amount" type="number">
Run Code Online (Sandbox Code Playgroud)

<input v-model="amount"
        oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
        type = "number"
        maxlength = "10"
/>
Run Code Online (Sandbox Code Playgroud)

  • 太棒了,找这个已经好几个小时了。 (3认同)

itt*_*tus 13

我们可以<input>手动控制值:

 <input
  type="number"
  :value="amount"
  @input="updateValue"
/>
Run Code Online (Sandbox Code Playgroud)

并检查 updateValue 方法:

  data() {
    return {
      amount: 7800
    }
  },
  methods: {
    updateValue(event) {
      const value = event.target.value
      console.log(value, this.amount)
      if (String(value).length <= 10) {
        this.amount = value
      }
      this.$forceUpdate()
    }
  }
Run Code Online (Sandbox Code Playgroud)

请注意,this.$forceUpdate()当用户输入超过 10 个字符时,用于使组件重新渲染。

Codepen 上的演示

  • 我更新了答案。`v-model` 是 `:value` 和 `@input` 的简写 (2认同)
  • 这个答案解决了我的问题,但我无法逃避这是一个黑客的想法。文档说“如果你发现自己需要在 Vue 中强制更新,在 99.99% 的情况下,你在某个地方犯了错误。” 2021年有没有更好的方法来解决这个问题? (2认同)