动态获取ref绑定的组件实例
在 Vue 3 中,如果使用动态 ref,可以通过 this.$refs 或 template refs 来获取。因为 ref 是动态的,需要使用对应的键名来访问。
一、示例代码
假设有一个列表,每个列表项都有一个 <el-upload> 组件,并且为每个组件动态设置了 ref:
<template>
<div v-for="(item, index) in items" :key="index">
<el-upload :ref="`uploadRef${index}`"/>
</div>
</template>
<script>
export default {
data() {
return {
items: [/* your data */]
};
},
methods: {
getUploadRef(index) {
// 获取动态 ref
const refName = `uploadRef${index}`;
const uploadComponent = this.$refs[refName];
console.log(uploadComponent);
return uploadComponent;
}
}
};
</script>
解释
-
动态
ref名称::ref="uploadRef${index}"为每个el-upload组件生成了一个动态ref名称,比如uploadRef0、uploadRef1等。 -
获取动态
ref: 使用this.$refs[refName]来访问ref。refName是动态生成的ref名称,比如uploadRef0。通过传递index,你可以访问相应的el-upload组件实例。 -
调用方法: 你可以在需要的时候调用
getUploadRef(index)方法来获取指定el-upload组件的引用。
二、注意事项
-
this.$refs是 Vue 2 和 Vue 3 都支持的特性,用于获取组件或 DOM 元素的引用。 -
在 Vue 3 中推荐使用 模板引用 (
template refs),因为它提供了更强的类型支持和灵活性。如果你使用的是组合式 API,ref的获取方式稍有不同,但this.$refs在选项式 API 中仍然有效。
三、Vue 3 组合式 API 的实现
如果使用 Vue 3 的组合式 API,获取动态 ref 的方式如下:
<template>
<div v-for="(item, index) in items" :key="index">
<el-upload :ref="el => uploadRefs[index] = el"/>
</div>
</template>
<script>
import { ref } from 'vue';
const items = ref([/* your data */]);
const uploadRefs = ref([]);
const getUploadRef = (index) => {
return uploadRefs.value[index];
};
</script>
在这种情况下,uploadRefs 是一个数组,存储每个 el-upload 组件的引用,你可以通过 index 来获取相应的 ref。

浙公网安备 33010602011771号