在 Vue 3 中,如果使用动态 ref,可以通过 this.$refstemplate 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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

解释

  1. 动态 ref 名称: :ref="uploadRef${index}" 为每个 el-upload 组件生成了一个动态 ref 名称,比如 uploadRef0uploadRef1 等。
  2. 获取动态 ref: 使用 this.$refs[refName] 来访问 refrefName 是动态生成的 ref 名称,比如 uploadRef0。通过传递 index,你可以访问相应的 el-upload 组件实例。
  3. 调用方法: 你可以在需要的时候调用 getUploadRef(index) 方法来获取指定 el-upload 组件的引用。

二、注意事项

  • this.$refs
  • 在 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>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

在这种情况下,uploadRefs 是一个数组,存储每个 el-upload 组件的引用,你可以通过 index 来获取相应的 ref