You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3组合式API中如何访问$refs数组?动态表单焦点跳转遇阻

解决方案

1. 替换this.$refs:在Vue3 Composition API中使用refs数组

Vue3的setup函数中不存在this,无法通过this.$refs访问DOM元素,需要直接创建一个ref数组来收集所有输入框的DOM实例:

setup() {
  const inputs = ref(["", "", "", "", ""]);
  // 创建ref数组存储输入框DOM元素
  const inputRefs = ref([]);

  const handleInput = (index) => {
    // 强制过滤非数字输入
    inputs.value[index] = inputs.value[index].replace(/\D/g, "");
    
    if (inputs.value[index] && index < inputs.value.length - 1) {
      // 跳转到下一个输入框
      inputRefs.value[index + 1]?.focus();
    } else if (index === inputs.value.length - 1 && inputs.value[index]) {
      // 最后一个输入框填满后触发提交
      handleSubmit();
    }
  };

  const handleSubmit = () => {
    // 拼接所有输入值,执行提交逻辑
    const formValue = inputs.value.join("");
    console.log("提交内容:", formValue);
    // 这里添加你的表单提交代码,比如调用接口
  };

  return {
    inputs,
    handleInput,
    inputRefs,
    handleSubmit
  };
}

2. 修改模板中的ref绑定方式

在v-for循环中,需要用函数式ref将每个输入框的DOM元素精准存入inputRefs数组,避免字符串ref可能导致的顺序混乱问题:

<div v-for="(input, index) in inputs" :key="index">
  <input
    type="text"
    v-model="inputs[index]"
    @input="handleInput(index)"
    :ref="el => { if (el) inputRefs[index] = el }"
    maxlength="1"
    inputmode="numeric"
    pattern="[0-9]"
  />
</div>

关键细节说明

  • 非数字过滤:用replace(/\D/g, "")直接清除非数字输入,比仅依赖pattern属性更可靠(pattern仅用于表单验证,不会阻止用户输入非数字字符)。
  • 安全焦点跳转:使用?.可选链操作符,避免数组越界时抛出报错。
  • 提交触发时机:当最后一个输入框填入有效数字后,自动调用提交函数,完成表单提交流程。

内容的提问来源于stack exchange,提问作者mrbf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:57:23