Vue3 + TypeScript + Element Plus + el-input 输入框列表按回车聚焦到下一行

应用效果:从第一行输入1,按回车,聚焦到第二行输入2,按回车,聚焦到第三行……

Vue3 + TypeScript + Element Plus + el-input 输入框列表按回车聚焦到下一行_第1张图片

一、通过元素 id,聚焦到下一行的输入框

关键技术点:

1、动态设置元素 id 属性为::id="`input-apply-amount-${(option as IReagentOption).id}`"

2、设置回车监听:@keyup.enter.native="onEnterPressDown((option as IReagentOption).id)"

                

3、通过 document.getElementById 获取到指定元素

4、focus 和 select,聚焦、全选

// 通过元素 id,聚焦到下一行的输入框
const focusNextRowByElementId = (objId: number) => {
  // 通过 objId 获取当前行索引
  let currentRowIndex = selectedOptionIds.value.indexOf(objId);
  // 下一行的输入框
  let nextInput: HTMLInputElement;
  if (currentRowIndex + 1 < selectedOptionIds.value.length) {
    // 下一行索引的 objId
    let nextRowObjId = selectedOptionIds.value[currentRowIndex + 1];
    nextInput = document.getElementById(`input-apply-amount-${nextRowObjId}`) as HTMLInputElement;
  } else {
    // 最后一行聚焦到申领用途输入框
    nextInput = document.getElementById("transfer-right-footer-purpose-input") as HTMLInputElement;
  }
  nextInput?.focus();
  nextInput?.select();
};

二、通过元素 ref,聚焦到下一行的输入框

关键技术点:

1、动态设置元素 ref 属性为::ref="`input-apply-amount-${(option as IReagentOption).id}`"

2、设置回车监听:@keyup.enter.native="onEnterPressDown((option as IReagentOption).id)"

                

3、通过 getCurrentInstance() 获取当前组件实例,再通过 refs 获取到元素列表

4、focus 和 select,聚焦、全选

实例完整代码:



你可能感兴趣的:(typescript,javascript,前端)