【问题标题】:Input type max length based on what function value输入类型最大长度基于什么函数值
【发布时间】:2021-10-25 18:08:14
【问题描述】:

我有一个看起来像的对象数组

 {
    value: "text",
    length: 50,
    image_url: textPassword,
    type: "text"
  },
  {
    value: "number_lock_3",
    length: 3,
    image_url: numberLock3,
    type: "number"
  },

在我的 html 中,我有一个输入

passwordType() 是上述对象之一。

这仅在类型为文本时有效。

<input 

:type="passwordType().type"
:maxlength="passwordType().length"

 />

我正在尝试为输入设置 maxlength,但只要类型为数字,maxlength 就不起作用,是否有任何自定义方法可用于根据 passwordType().length 为输入设置最大长度?

【问题讨论】:

标签: vue.js vuejs3


【解决方案1】:

使用pattern 仅适用于验证

您也可以尝试max(下面的示例),但它允许您输入任何值并仅在使用?/?按钮时强制执行最大值

但最可靠的解决方案可能是使用@input 事件侦听器来修剪值。

Vue.createApp({
  data: () => ({
    passwordType: {
      value: "number_lock_3",
      length: 3,
      type: "number"
    }
  }),
  methods: {
    getMax(length) {
      return parseInt(''.padStart(length, '9'))
    },
    onKeydown(target, length) {
      target.value = target.value.substr(0, length)
    }
  },
}).mount("#app");
<script src="https://unpkg.com/vue@3.2.0/dist/vue.global.prod.js"></script>
<div id="app">
  <input :type="passwordType.type" :max="getMax(passwordType.length)" /> max ( {{getMax(passwordType.length)}}) <br />
  <input :type="passwordType.type" @input="(e)=>{onKeydown(e.target, passwordType.length)}" /> @input <br />

  <input v-model="passwordType.length" type="number" /> length
</div>

【讨论】:

  • 谢谢,这正是我需要的
猜你喜欢
  • 2020-01-05
  • 2017-08-25
  • 2022-01-03
  • 2014-12-15
  • 2012-06-02
  • 2017-10-19
  • 2016-05-22
  • 2020-08-26
  • 2020-05-04
相关资源
最近更新 更多