方法一:使用 ref数组
<template><div><div v-for="(item, index) in items" :key="index"><input ref="inputRefs" :placeholder="'Input ' + index" /></div><button @click="focusFirst">Focus First Input</button></div>
</template><script setup>
import { ref } from 'vue'// 定义一个 ref,用来存放 v-for 中的 input 元素
const inputRefs = ref([])const items = [1, 2, 3, 4]const focusFirst = () => {// inputRefs.value 是一个数组,包含所有循环中的 input DOM 元素if (inputRefs.value[0]) {inputRefs.value[0].focus()}
}
</script>
方法二:使用函数形式的 ref
<template><div><div v-for="(item, index) in items" :key="index"><input :ref="el => setItemRef(el, index)" :placeholder="'Input ' + index" /></div><button @click="focusInput(1)">Focus Input 1</button></div>
</template><script setup>
import { ref, onBeforeUpdate } from 'vue'const items = [1, 2, 3, 4]
const itemRefs = ref({}) // 用对象存储,以 index 或 id 为 key// 用于存储 ref 的函数
const setItemRef = (el, index) => {if (el) {itemRefs.value[index] = el}
}// 在组件更新前清空旧的 ref,避免重复引用(重要!)
onBeforeUpdate(() => {itemRefs.value = {}
})const focusInput = (index) => {const el = itemRefs.value[index]if (el) {el.focus()}
}
</script>