使用 Vue 在当前字段上达到 maxLength 时转到下一个输入字段?

Go to next input field when maxLength is reached on current field using Vue?

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

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

很确定这在用户体验方面不被推荐,但这里有一个关于如何实现它的例子: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 中的推荐方式为 select 一些 DOM 元素)。然后,当我们到达 max 时,我们将当前的输入 data-index 增加一,这使我们能够转到下一个输入。

PS: ?. 语法是 optional chaining,它可以防止丑陋的代码,并允许在没有 next input once max 的情况下避免错误已达到。

PS:不确定是否有办法直接获取其 @input 事件上元素的 $refs,但如果有,我没有找到方法去做。