当你使用动态绑定的 ref 时,
this.$refs
会返回一个
数组
,而不是直接返回组件实例。因此,你需要通过数组索引
来访问具体的组件实例。
示例代码:
bash
<template>
<div>
<!-- 动态绑定 ref(v-for 循环场景) -->
<div v-for="(item, index) in items" :key="index">
<input
:ref="el => { setItemRef(el, index) }"
v-model="item.value"
@blur="handleBlur(index)"
>
</div>
<button @click="showRefs">查看所有 refs</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ value: '第一个输入框' },
{ value: '第二个输入框' },
{ value: '第三个输入框' }
],
// 存储动态 ref 的数组
inputRefs: []
}
},
methods: {
// 动态设置 ref 的回调函数
setItemRef(el, index) {
if (el) {
this.inputRefs[index] = el
}
},
// 通过索引访问具体实例
handleBlur(index) {
const currentInput = this.inputRefs[index]
console.log('失去焦点的输入框:', currentInput.value)
},
showRefs() {
// 两种访问方式:
// 方式1:通过我们自己维护的数组
console.log('自定义数组:', this.inputRefs)
// 方式2:通过官方 $refs(需注意是数组)
console.log('$refs 数组:', this.$refs.dynamicInput)
console.log('第一个输入框实例:', this.$refs.dynamicInput)
}
}
}
</script>