在 Vue 3 中,如果使用动态 ref
,可以通过 this.$refs
或 template refs
来获取。因为 ref
是动态的,需要使用对应的键名来访问。
一、示例代码
假设有一个列表,每个列表项都有一个 <el-upload>
组件,并且为每个组件动态设置了 ref
:
解释
- 动态
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 3 中推荐使用 模板引用 (
template refs
),因为它提供了更强的类型支持和灵活性。如果你使用的是组合式 API,ref
的获取方式稍有不同,但this.$refs
在选项式 API 中仍然有效。
三、Vue 3 组合式 API 的实现
如果使用 Vue 3 的组合式 API,获取动态 ref
的方式如下:
在这种情况下,uploadRefs
是一个数组,存储每个 el-upload
组件的引用,你可以通过 index
来获取相应的 ref
。