【问题标题】:Go to next input field when maxLength is reached on current field using Vue?使用Vue在当前字段上达到maxLength时转到下一个输入字段?
【发布时间】:2021-04-30 09:05:12
【问题描述】:

我在 Vue 中有一个表单,它有一些组合输入,用于电话号码输入的样式原因。我的问题是用户必须点击标签才能转到电话号码的下一个输入字段。有没有办法检查当前和输入的最大长度,当满足时转到下一个输入?

<div class="combined-input combined-input--phone" :class="{'error--input': phoneInvalid('patientInformation')}">
  <div class="open-parenthesis"></div>

  <input type="text" id="phoneArea" maxlength="3" @blur="$v.formData.patientInformation.phone.$touch()" v-model.trim="$v.formData.patientInformation.phone.area.$model">

  <div class="close-parenthesis"></div>

  <input type="text" id="phoneA" maxlength="3" @blur="$v.formData.patientInformation.phone.$touch()" v-model.trim="$v.formData.patientInformation.phone.a.$model">

  <div class="dash"></div>

  <input type="text" id="phoneB" maxlength="4" @blur="$v.formData.patientInformation.phone.$touch()" v-model.trim="$v.formData.patientInformation.phone.b.$model">
</div>

【问题讨论】:

    标签: javascript html vue.js nuxt.js vuelidate


    【解决方案1】:

    非常确定不建议在 UX 方面这样做,但这里有一个关于如何实现它的示例:https://codesandbox.io/s/move-to-next-input-on-condition-103b5?file=/src/App.vue

    有用代码的主要部分是

    focusNextOncePopulated(event, max) {
      if (event.target.value.length === max) {
        const nextElement = this.$refs?.[`input-${Number(event.target.dataset.index) +1}`]
        if (nextElement) nextElement.focus()
      }
    },
    

    说明:每次输入一个字符时,您都会检查字段的长度是否达到了您在特定输入上设置的最大值。如果是,并且有与兄弟相似的输入,则将其聚焦。
    在性能方面,添加几毫秒的 debounce 也很好。

    编辑:为了防止在 DOM 中尝试找到正确的下一个 input 时出现任何问题,我们在每个输入上设置了一些参考(推荐在 Vue 中选择一些 DOM 元素的方式)。然后,当我们到达max 时,我们将当前的输入data-index 加一,这使我们能够转到下一个输入。

    PS:?. 语法是optional chaining,它可以防止丑陋的代码,并且一旦到达max 就可以避免在没有下一个input 时出现错误。

    PS:不确定是否有办法直接获取 @input 事件上的元素的 $refs,但如果有,我不知道该怎么做。

    【讨论】:

    • 太好了!当然,我的 nextSibling 是 div 右括号或 div dash...lol....不过感谢您的建议!
    • 您需要为下一个输入设置选择器。刚刚更新了我的答案,以可能的方式做到这一点。它有点冗长,但允许返回上一个字段并再次关注下一个字段,而不是我们离开的最后一个字段。如果你想要以后的行为,在data 中设置一个状态并一直递增它可能是一个解决方案。
    猜你喜欢
    • 1970-01-01
    • 2012-11-23
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多